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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🧺 fix: Skip Priming Denied File Search Resources (#15699)
Danny Avila29971f188ab2
diff --git a/api/server/controllers/agents/__tests__/openai.spec.js b/api/server/controllers/agents/__tests__/openai.spec.jsindex 494ed4e3b5..42be10e7f4 100644--- a/api/server/controllers/agents/__tests__/openai.spec.js+++ b/api/server/controllers/agents/__tests__/openai.spec.js@@ -1657,4 +1657,68 @@ describe('OpenAIChatCompletionController', () => {});});});++ describe('file search role gating', () => {+ const setCapabilities = (capabilities) => {+ req.config.endpoints.agents.capabilities = capabilities;+ };++ it('reports file search available when the capability and the grant agree', async () => {+ const { initializeAgent } = require('@librechat/api');+ setCapabilities(['file_search']);++ await OpenAIChatCompletionController(req, res);++ expect(initializeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ fileSearchAvailable: true }),+ expect.anything(),+ );+ });++ /** `initializeAgent` re-hydrates prior-turn `file_search` files from this+ * flag, so a denied role must reach it — dropping the tool downstream still+ * leaves the files read, their usage bumped and their resources primed. */+ it('withholds it when the role is denied FILE_SEARCH', async () => {+ const { initializeAgent, resolveToolRoleGrants } = require('@librechat/api');+ resolveToolRoleGrants.mockResolvedValueOnce({ runCode: true, fileSearch: false });+ setCapabilities(['file_search']);++ await OpenAIChatCompletionController(req, res);++ expect(initializeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ fileSearchAvailable: false }),+ expect.anything(),+ );+ });++ /** Both flags are false without their capability, so the role read would be+ * pure load on every request. */+ it('reads no role at all when neither capability is enabled', async () => {+ const { initializeAgent, resolveToolRoleGrants } = require('@librechat/api');+ setCapabilities([]);++ await OpenAIChatCompletionController(req, res);++ expect(resolveToolRoleGrants).not.toHaveBeenCalled();+ expect(initializeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ fileSearchAvailable: false, codeEnvAvailable: false }),+ expect.anything(),+ );+ });++ /** One lookup answers both grants, so enabling either capability pays for+ * the other's pairing too. */+ it('pairs both flags from a single role read', async () => {+ const { initializeAgent, resolveToolRoleGrants } = require('@librechat/api');+ setCapabilities(['file_search', 'execute_code']);++ await OpenAIChatCompletionController(req, res);++ expect(resolveToolRoleGrants).toHaveBeenCalledTimes(1);+ expect(initializeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ fileSearchAvailable: true, codeEnvAvailable: true }),+ expect.anything(),+ );+ });+ });});diff --git a/api/server/controllers/agents/__tests__/responses.unit.spec.js b/api/server/controllers/agents/__tests__/responses.unit.spec.jsindex 31d1eecbad..42c56f763e 100644--- a/api/server/controllers/agents/__tests__/responses.unit.spec.js+++ b/api/server/controllers/agents/__tests__/responses.unit.spec.js@@ -2198,4 +2198,68 @@ describe('createResponse controller', () => {});});});++ describe('file search role gating', () => {+ const setCapabilities = (capabilities) => {+ req.config.endpoints.agents.capabilities = capabilities;+ };++ it('reports file search available when the capability and the grant agree', async () => {+ const { initializeAgent } = require('@librechat/api');+ setCapabilities(['file_search']);++ await createResponse(req, res);++ expect(initializeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ fileSearchAvailable: true }),+ expect.anything(),+ );+ });++ /** `initializeAgent` re-hydrates prior-turn `file_search` files from this+ * flag, so a denied role must reach it — dropping the tool downstream still+ * leaves the files read, their usage bumped and their resources primed. */+ it('withholds it when the role is denied FILE_SEARCH', async () => {+ const { initializeAgent, resolveToolRoleGrants } = require('@librechat/api');+ resolveToolRoleGrants.mockResolvedValueOnce({ runCode: true, fileSearch: false });+ setCapabilities(['file_search']);++ await createResponse(req, res);++ expect(initializeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ fileSearchAvailable: false }),+ expect.anything(),+ );+ });++ /** Both flags are false without their capability, so the role read would be+ * pure load on every request. */+ it('reads no role at all when neither capability is enabled', async () => {+ const { initializeAgent, resolveToolRoleGrants } = require('@librechat/api');+ setCapabilities([]);++ await createResponse(req, res);++ expect(resolveToolRoleGrants).not.toHaveBeenCalled();+ expect(initializeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ fileSearchAvailable: false, codeEnvAvailable: false }),+ expect.anything(),+ );+ });++ /** One lookup answers both grants, so enabling either capability pays for+ * the other's pairing too. */+ it('pairs both flags from a single role read', async () => {+ const { initializeAgent, resolveToolRoleGrants } = require('@librechat/api');+ setCapabilities(['file_search', 'execute_code']);++ await createResponse(req, res);++ expect(resolveToolRoleGrants).toHaveBeenCalledTimes(1);+ expect(initializeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ fileSearchAvailable: true, codeEnvAvailable: true }),+ expect.anything(),+ );+ });+ });});diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.jsindex d47c140983..48ae4831c6 100644--- a/api/server/controllers/agents/openai.js+++ b/api/server/controllers/agents/openai.js@@ -491,13 +491,16 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {const enabledCapabilities = new Set(agentsEConfig?.capabilities);const codeCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.execute_code);+ const fileSearchCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.file_search);/** Started before the memory read rather than awaited on its own line, so* the role lookup overlaps that query instead of preceding it. Skipped- * when the deployment has the capability off — the flag is false either- * way, so the read would be pure load on every request. */- const toolRoleGrants = codeCapabilityEnabled- ? resolveToolRoleGrants({ req, getRoleByName: db.getRoleByName })- : null;+ * when the deployment has both capabilities off — both flags are false+ * either way, so the read would be pure load on every request. One+ * lookup answers both. */+ const toolRoleGrants =+ codeCapabilityEnabled || fileSearchCapabilityEnabled+ ? resolveToolRoleGrants({ req, getRoleByName: db.getRoleByName })+ : null;const memoryAvailable = await resolveMemoryAvailability({enabledCapabilities,memoryConfig: appConfig?.memory,@@ -508,6 +511,11 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {* `bash_tool`, `read_file` and the workspace file tools from this flag,* and forwards the code-environment context to their handlers. */const codeEnvAvailable = codeCapabilityEnabled && (await toolRoleGrants)?.runCode === true;+ /** The same pairing for the other gated tool, read only by the resend-file+ * priming: `false` skips re-hydrating prior-turn `file_search` files for+ * a tool the loader is about to drop. */+ const fileSearchAvailable =+ fileSearchCapabilityEnabled && (await toolRoleGrants)?.fileSearch === true;const skillsCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.skills);const ephemeralSkillsToggle = request.ephemeralAgent?.skills === true;const accessibleSkillIds = skillsCapabilityEnabled@@ -573,6 +581,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {ephemeralSkillsToggle,}),codeEnvAvailable,+ fileSearchAvailable,backgroundToolsAvailable: enabledCapabilities.has(AgentCapabilities.run_in_background),toolIntentsAvailable: enabledCapabilities.has(AgentCapabilities.tool_intents),statefulSessionsAvailable: enabledCapabilities.has(@@ -652,6 +661,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {skillStates,defaultActiveOnShare,codeEnvAvailable,+ fileSearchAvailable,backgroundToolsAvailable: enabledCapabilities.has(AgentCapabilities.run_in_background),toolIntentsAvailable: enabledCapabilities.has(AgentCapabilities.tool_intents),statefulSessionsAvailable: enabledCapabilities.has(diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.jsindex 7ca3581df5..dd6fb2e7d4 100644--- a/api/server/controllers/agents/responses.js+++ b/api/server/controllers/agents/responses.js@@ -738,13 +738,16 @@ const executeResponse = async (envelope, { req, res }) => {const enabledCapabilities = new Set(agentsEConfig?.capabilities);const codeCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.execute_code);+ const fileSearchCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.file_search);/** Started before the memory read rather than awaited on its own line, so* the role lookup overlaps that query instead of preceding it. Skipped- * when the deployment has the capability off — the flag is false either- * way, so the read would be pure load on every request. */- const toolRoleGrants = codeCapabilityEnabled- ? resolveToolRoleGrants({ req, getRoleByName: db.getRoleByName })- : null;+ * when the deployment has both capabilities off — both flags are false+ * either way, so the read would be pure load on every request. One+ * lookup answers both. */+ const toolRoleGrants =+ codeCapabilityEnabled || fileSearchCapabilityEnabled+ ? resolveToolRoleGrants({ req, getRoleByName: db.getRoleByName })+ : null;const memoryAvailable = await resolveMemoryAvailability({enabledCapabilities,memoryConfig: appConfig?.memory,@@ -755,6 +758,11 @@ const executeResponse = async (envelope, { req, res }) => {* `bash_tool`, `read_file` and the workspace file tools from this flag,* and forwards the code-environment context to their handlers. */const codeEnvAvailable = codeCapabilityEnabled && (await toolRoleGrants)?.runCode === true;+ /** The same pairing for the other gated tool, read only by the resend-file+ * priming: `false` skips re-hydrating prior-turn `file_search` files for+ * a tool the loader is about to drop. */+ const fileSearchAvailable =+ fileSearchCapabilityEnabled && (await toolRoleGrants)?.fileSearch === true;const skillsCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.skills);const ephemeralSkillsToggle = request.ephemeralAgent?.skills === true;const accessibleSkillIds = skillsCapabilityEnabled@@ -820,6 +828,7 @@ const executeResponse = async (envelope, { req, res }) => {ephemeralSkillsToggle,}),codeEnvAvailable,+ fileSearchAvailable,backgroundToolsAvailable: enabledCapabilities.has(AgentCapabilities.run_in_background),toolIntentsAvailable: enabledCapabilities.has(AgentCapabilities.tool_intents),statefulSessionsAvailable: enabledCapabilities.has(@@ -899,6 +908,7 @@ const executeResponse = async (envelope, { req, res }) => {skillStates,defaultActiveOnShare,codeEnvAvailable,+ fileSearchAvailable,backgroundToolsAvailable: enabledCapabilities.has(AgentCapabilities.run_in_background),toolIntentsAvailable: enabledCapabilities.has(AgentCapabilities.tool_intents),statefulSessionsAvailable: enabledCapabilities.has(diff --git a/api/server/services/Endpoints/agents/addedConvo.js b/api/server/services/Endpoints/agents/addedConvo.jsindex 71c2702587..8a9e10d92c 100644--- a/api/server/services/Endpoints/agents/addedConvo.js+++ b/api/server/services/Endpoints/agents/addedConvo.js@@ -61,6 +61,9 @@ const loadAddedAgent = (params) =>* @param {boolean} [params.codeEnvAvailable] - `execute_code` capability flag;* forwarded verbatim to the added agent's `initializeAgent`. @see* InitializeAgentParams.codeEnvAvailable for full semantics.+ * @param {boolean} [params.fileSearchAvailable] - `file_search` capability AND+ * the caller's `FILE_SEARCH` grant; forwarded verbatim alongside+ * `codeEnvAvailable`. @see InitializeAgentParams.fileSearchAvailable.* @param {boolean} [params.statefulSessionsAvailable] - `stateful_code_sessions`* capability flag; forwarded verbatim alongside `codeEnvAvailable`.* @returns {Promise<{userMCPAuthMap: Object|undefined}>} The updated userMCPAuthMap@@ -89,6 +92,7 @@ const processAddedConvo = async ({skillStates,defaultActiveOnShare,codeEnvAvailable,+ fileSearchAvailable,backgroundToolsAvailable,toolIntentsAvailable,statefulSessionsAvailable,@@ -189,6 +193,7 @@ const processAddedConvo = async ({ephemeralSkillsToggle,}),codeEnvAvailable,+ fileSearchAvailable,backgroundToolsAvailable,toolIntentsAvailable,statefulSessionsAvailable,diff --git a/api/server/services/Endpoints/agents/addedConvo.spec.js b/api/server/services/Endpoints/agents/addedConvo.spec.jsindex a7b391acb5..c2c6b69121 100644--- a/api/server/services/Endpoints/agents/addedConvo.spec.js+++ b/api/server/services/Endpoints/agents/addedConvo.spec.js@@ -119,6 +119,23 @@ describe('processAddedConvo', () => {);});+ /** The added convo re-hydrates the same conversation's prior-turn files, so a+ * denied `FILE_SEARCH` grant has to travel with it — otherwise the parallel+ * agent primes the search files the primary just skipped. `undefined` stays+ * `undefined`, which leaves priming unconditional for callers that never+ * resolved the grant. */+ it.each([true, false, undefined])(+ 'forwards fileSearchAvailable=%s verbatim to the added-convo initializeAgent call',+ async (fileSearchAvailable) => {+ await processAddedConvo(baseParams({ fileSearchAvailable }));++ expect(mockInitializeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ fileSearchAvailable }),+ expect.anything(),+ );+ },+ );+it('forwards codeEnvAvailable=false verbatim (not coerced to undefined)', async () => {/* Symmetric coverage: if the runtime gate is off for the primary, theparallel agent must not accidentally re-enable code execution via adiff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.jsindex 3f29d28d30..9d73e6d711 100644--- a/api/server/services/Endpoints/agents/initialize.js+++ b/api/server/services/Endpoints/agents/initialize.js@@ -228,14 +228,16 @@ const initializeClient = async ({const enabledCapabilities = new Set(appConfig?.endpoints?.[EModelEndpoint.agents]?.capabilities);const skillsCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.skills);const codeCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.execute_code);+ const fileSearchCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.file_search);/** Started here but joined into the startup `Promise.all` below rather than- * awaited inline: `codeEnvAvailable` is not read until agent construction, so- * the role lookup overlaps the memory, skill and conversation queries instead- * of delaying them. Skipped entirely when the deployment has the capability- * off, since the flag is false either way. */- const toolRoleGrantsPromise = codeCapabilityEnabled- ? resolveToolRoleGrants({ req, getRoleByName: db.getRoleByName, context: 'initializeClient' })- : null;+ * awaited inline: neither flag is read until agent construction, so the role+ * lookup overlaps the memory, skill and conversation queries instead of+ * delaying them. Skipped entirely when the deployment has both capabilities+ * off, since both flags are false either way. One lookup answers both. */+ const toolRoleGrantsPromise =+ codeCapabilityEnabled || fileSearchCapabilityEnabled+ ? resolveToolRoleGrants({ req, getRoleByName: db.getRoleByName, context: 'initializeClient' })+ : null;const backgroundToolsAvailable = enabledCapabilities.has(AgentCapabilities.run_in_background);const toolIntentsAvailable = enabledCapabilities.has(AgentCapabilities.tool_intents);const deferredToolsAvailable = enabledCapabilities.has(AgentCapabilities.deferred_tools);@@ -537,6 +539,11 @@ const initializeClient = async ({* forwards the code-environment context to their handlers — so the grant has* to travel with the flag, not just with the tool list. */const codeEnvAvailable = codeCapabilityEnabled && toolRoleGrants?.runCode === true;+ /** The same pairing for the other gated tool. Read only by the resend-file+ * priming inside `initializeAgent`: `false` skips re-hydrating prior-turn+ * `file_search` files, whose usage counters would otherwise be bumped and+ * whose resources primed for a tool the loader is about to drop. */+ const fileSearchAvailable = fileSearchCapabilityEnabled && toolRoleGrants?.fileSearch === true;const agentConfigs = new Map();const allowedProviders = new Set(appConfig?.endpoints?.[EModelEndpoint.agents]?.allowedProviders);@@ -621,6 +628,7 @@ const initializeClient = async ({accessibleSkillIds: primaryScopedSkillIds,skillAuthoringAvailable: primarySkillAuthoringAvailable,codeEnvAvailable,+ fileSearchAvailable,backgroundToolsAvailable,toolIntentsAvailable,statefulSessionsAvailable,@@ -703,6 +711,7 @@ const initializeClient = async ({skillStates,defaultActiveOnShare,codeEnvAvailable,+ fileSearchAvailable,backgroundToolsAvailable,toolIntentsAvailable,statefulSessionsAvailable,@@ -781,6 +790,7 @@ const initializeClient = async ({skillStates,defaultActiveOnShare,codeEnvAvailable,+ fileSearchAvailable,backgroundToolsAvailable,toolIntentsAvailable,statefulSessionsAvailable,@@ -1149,6 +1159,7 @@ const initializeClient = async ({ephemeralSkillsToggle,}),codeEnvAvailable,+ fileSearchAvailable,backgroundToolsAvailable,toolIntentsAvailable,statefulSessionsAvailable,diff --git a/api/server/services/__tests__/toolCapabilityGates.spec.js b/api/server/services/__tests__/toolCapabilityGates.spec.jsindex ccad21b00f..d50f1ba1e7 100644--- a/api/server/services/__tests__/toolCapabilityGates.spec.js+++ b/api/server/services/__tests__/toolCapabilityGates.spec.js@@ -26,20 +26,24 @@ const CLASSIFIED = {// -- Gates: capability AND grant --------------------------------------------/** 7 gates + 2 map entries + 2 warning-list entries. */'api/server/services/ToolService.js': 11,- /** `codeEnvAvailable`, paired after the startup batch. */- 'api/server/services/Endpoints/agents/initialize.js': 1,- /** `codeEnvAvailable` for the OpenAI-compatible route. */- 'api/server/controllers/agents/openai.js': 1,- /** `codeEnvAvailable` for the Responses route. */- 'api/server/controllers/agents/responses.js': 1,+ /** `codeEnvAvailable` and `fileSearchAvailable`, both paired after the+ * startup batch from the one grant read that batch joins. */+ 'api/server/services/Endpoints/agents/initialize.js': 2,+ /** `codeEnvAvailable` and `fileSearchAvailable` for the OpenAI-compatible+ * route, both paired with the shared grant read. */+ 'api/server/controllers/agents/openai.js': 2,+ /** `codeEnvAvailable` and `fileSearchAvailable` for the Responses route,+ * both paired with the shared grant read. */+ 'api/server/controllers/agents/responses.js': 2,/** `codeEnvAvailable` for the memory-agent initializer. */'api/server/controllers/agents/client.js': 1,/** Upload processing: the code-environment and file-search branches. */'api/server/services/Files/process.js': 2,/** Agent-management upload purposes. */'api/server/routes/agents/management.js': 2,- /** One gate, paired when the embedder wires `getRoleByName`; one in a comment. */- 'packages/api/src/agents/openai/service.ts': 2,+ /** Two gates, each paired when the embedder wires `getRoleByName`; one in a+ * comment. */+ 'packages/api/src/agents/openai/service.ts': 3,// -- Not gates ---------------------------------------------------------------/** The upload-resource map entry, and one mention in a doc comment. */diff --git a/packages/api/src/agents/discovery.spec.ts b/packages/api/src/agents/discovery.spec.tsindex dce09b5425..616c3cf2e1 100644--- a/packages/api/src/agents/discovery.spec.ts+++ b/packages/api/src/agents/discovery.spec.ts@@ -273,6 +273,41 @@ describe('discoverConnectedAgents', () => {);});+ /** A handoff agent re-hydrates the same conversation's prior-turn files, so+ * it has to prime them on exactly the terms its parent did — forgetting this+ * gives a denied role its search files back one hop later. */+ it.each([true, false, undefined])(+ 'forwards fileSearchAvailable=%s verbatim to every handoff initializeAgent call',+ async (fileSearchAvailable) => {+ const primaryConfig = makeConfig('A', [{ from: 'A', to: 'B', edgeType: 'handoff' }]);+ const getAgent = jest.fn(async () => makeAgent('B', []));+ const checkPermission = jest.fn().mockResolvedValue(true);++ await discoverConnectedAgents(+ {+ req: makeReq(),+ res: makeRes(),+ primaryConfig,+ allowedProviders: new Set(),+ modelsConfig: { openai: ['gpt-4o'] },+ loadTools: jest.fn(),+ fileSearchAvailable,+ },+ {+ getAgent,+ checkPermission,+ logViolation: jest.fn(),+ db: {} as never,+ },+ );++ expect(mockInitializeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ fileSearchAvailable }),+ expect.anything(),+ );+ },+ );+it('forwards normalized request metadata to every handoff initializeAgent call', async () => {const primaryConfig = makeConfig('A', [{ from: 'A', to: 'B', edgeType: 'handoff' }]);const getAgent = jest.fn(async () => makeAgent('B', []));diff --git a/packages/api/src/agents/discovery.ts b/packages/api/src/agents/discovery.tsindex f525481f23..45766568a5 100644--- a/packages/api/src/agents/discovery.ts+++ b/packages/api/src/agents/discovery.ts@@ -105,6 +105,13 @@ export interface DiscoverConnectedAgentsParams {* code-execution tooling even though their parent had it.*/codeEnvAvailable?: InitializeAgentParams['codeEnvAvailable'];+ /**+ * Sibling of `codeEnvAvailable` for the other role-gated tool — the+ * `file_search` capability AND the caller's `FILE_SEARCH` grant. Forwarded+ * verbatim so a handoff agent re-hydrates prior-turn search files on exactly+ * the terms its parent did.+ */+ fileSearchAvailable?: InitializeAgentParams['fileSearchAvailable'];/** Sibling of `codeEnvAvailable` — the `stateful_code_sessions` capability flag, forwarded to every handoff `initializeAgent`. */statefulSessionsAvailable?: InitializeAgentParams['statefulSessionsAvailable'];/** Deployment policy for stateful workspace scopes, forwarded unchanged to every referenced agent. */@@ -243,6 +250,7 @@ async function initializeReferencedAgent(skillStates: params.skillStates,defaultActiveOnShare: params.defaultActiveOnShare,codeEnvAvailable: params.codeEnvAvailable,+ fileSearchAvailable: params.fileSearchAvailable,backgroundToolsAvailable: params.backgroundToolsAvailable,toolIntentsAvailable: params.toolIntentsAvailable,statefulSessionsAvailable: params.statefulSessionsAvailable,diff --git a/packages/api/src/agents/initialize.files.spec.ts b/packages/api/src/agents/initialize.files.spec.tsindex 45045fb7b0..25f98bd1d4 100644--- a/packages/api/src/agents/initialize.files.spec.ts+++ b/packages/api/src/agents/initialize.files.spec.ts@@ -1,5 +1,6 @@+import { Tools, EToolResources } from 'librechat-data-provider';import type { IConversation } from '@librechat/data-schemas';-import { readResolvedConversationFiles } from './initialize';+import { readResolvedConversationFiles, resolveResendToolResources } from './initialize';import { PARTIAL_RESOLVED_CONVERSATION } from './guard';describe('readResolvedConversationFiles', () => {@@ -56,3 +57,52 @@ describe('readResolvedConversationFiles', () => {).toBeUndefined();});});++describe('resolveResendToolResources', () => {+ const resolve = (tools: string[], flags: { code: boolean; fileSearch?: boolean }) =>+ resolveResendToolResources({+ tools,+ codeEnvAvailable: flags.code,+ fileSearchAvailable: flags.fileSearch,+ });++ it('primes both gated tools when both flags allow them', () => {+ expect([+ ...resolve([Tools.execute_code, Tools.file_search], { code: true, fileSearch: true }),+ ]).toEqual([EToolResources.execute_code, EToolResources.file_search]);+ });++ it('drops only the tool whose flag is false', () => {+ expect([+ ...resolve([Tools.execute_code, Tools.file_search], { code: false, fileSearch: true }),+ ]).toEqual([EToolResources.file_search]);+ expect([+ ...resolve([Tools.execute_code, Tools.file_search], { code: true, fileSearch: false }),+ ]).toEqual([EToolResources.execute_code]);+ });++ it('primes neither when the role carries neither grant', () => {+ expect([+ ...resolve([Tools.execute_code, Tools.file_search], { code: false, fileSearch: false }),+ ]).toEqual([]);+ });++ /** Callers that never resolved the grant must keep priming as they did, or+ * adding the parameter would silently drop search files for every embedder+ * that does not pass it. */+ it('primes file search when the caller resolved no grant at all', () => {+ expect([...resolve([Tools.file_search], { code: false })]).toEqual([+ EToolResources.file_search,+ ]);+ });++ it('leaves ungated tool resources alone and ignores tools that map to none', () => {+ expect([...resolve([EToolResources.ocr, Tools.web_search], { code: false })]).toEqual([+ EToolResources.ocr,+ ]);+ });++ it('reports nothing for an agent with no tools', () => {+ expect([...resolveResendToolResources({ codeEnvAvailable: true })]).toEqual([]);+ });+});diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.tsindex 64d59e8422..4fc3a0a5a6 100644--- a/packages/api/src/agents/initialize.ts+++ b/packages/api/src/agents/initialize.ts@@ -225,6 +225,47 @@ export function readResolvedConversationFiles(return resolved.files ?? [];}+export interface ResolveResendToolResourcesParams {+ /** Tool names as configured on the agent. */+ tools?: string[] | null;+ /** `execute_code` capability AND the caller's `RUN_CODE` grant. */+ codeEnvAvailable: boolean;+ /**+ * `file_search` capability AND the caller's `FILE_SEARCH` grant. `undefined`+ * where the caller resolved neither, which leaves priming as it was.+ */+ fileSearchAvailable?: boolean;+}++/**+ * Tool resources whose prior-turn files this run re-hydrates on resend.+ *+ * Both role-gated tools are filtered here rather than after hydration, because+ * priming is not free: the files are read, their usage counters are bumped, and+ * they are primed into `tool_resources` for a tool the loader is about to drop.+ * Each flag is the deployment capability AND the role grant, so this reaches the+ * same verdict the loader will.+ */+export function resolveResendToolResources({+ tools,+ codeEnvAvailable,+ fileSearchAvailable,+}: ResolveResendToolResourcesParams): Set<EToolResources> {+ const toolResourceSet = new Set<EToolResources>();+ for (const tool of tools ?? []) {+ if (tool === Tools.execute_code && !codeEnvAvailable) {+ continue;+ }+ if (tool === Tools.file_search && fileSearchAvailable === false) {+ continue;+ }+ if (EToolResources[tool as keyof typeof EToolResources]) {+ toolResourceSet.add(EToolResources[tool as keyof typeof EToolResources]);+ }+ }+ return toolResourceSet;+}+function getMaxCatalogSkills(runtime: AgentExecutionContext): number | undefined {const endpoints = runtime.appConfig?.endpoints as| Record<string, { skills?: { maxCatalogSkills?: number } } | undefined>@@ -595,6 +636,14 @@ export interface InitializeAgentParams {skillAuthoringAvailable?: boolean;/** Whether the code execution environment is available (execute_code capability enabled) */codeEnvAvailable?: boolean;+ /**+ * Whether `file_search` is available to this caller — the capability AND the+ * `FILE_SEARCH` role grant. Read only when re-hydrating a conversation's+ * prior-turn files: `false` skips priming resources for a tool the loader will+ * drop anyway. Absent leaves priming unconditional, so a caller that has not+ * resolved the grant keeps its current behavior.+ */+ fileSearchAvailable?: boolean;/*** Whether the `run_in_background` capability is enabled for this run. When* true, tools the agent opted in via `tool_options[name].run_in_background`@@ -1014,18 +1063,14 @@ export async function initializeAgent(* on handoff agents would fail to find previously attached files.*/if (conversationId != null && resendFiles) {- const toolResourceSet = new Set<EToolResources>();- for (const tool of agent.tools ?? []) {- /** `effectiveCodeEnvAvailable` already carries the role grant, so a denied- * role skips the thread walk and the code-file hydration below rather- * than paying for resources the tool loader is about to drop. */- if (tool === Tools.execute_code && !effectiveCodeEnvAvailable) {- continue;- }- if (EToolResources[tool as keyof typeof EToolResources]) {- toolResourceSet.add(EToolResources[tool as keyof typeof EToolResources]);- }- }+ /** Both flags already carry their role grant, so a denied role skips the+ * thread walk and the hydration below rather than paying for resources the+ * tool loader is about to drop. */+ const toolResourceSet = resolveResendToolResources({+ tools: agent.tools,+ codeEnvAvailable: effectiveCodeEnvAvailable,+ fileSearchAvailable: params.fileSearchAvailable,+ });const getThreadMessages = db.getMessages;/** Falsy anchors cannot match a parent chain, so they get no walk. */diff --git a/packages/api/src/agents/openai/service.spec.ts b/packages/api/src/agents/openai/service.spec.tsindex 8c91c71212..9655ff1823 100644--- a/packages/api/src/agents/openai/service.spec.ts+++ b/packages/api/src/agents/openai/service.spec.ts@@ -1,5 +1,5 @@import { GraphEvents } from '@librechat/agents';-import { ErrorTypes } from 'librechat-data-provider';+import { ErrorTypes, Permissions, PermissionTypes } from 'librechat-data-provider';import type { FiltersConfig } from 'librechat-data-provider';import type { ChatCompletionDependencies } from './service';import { createAgentChatCompletion } from './service';@@ -355,6 +355,45 @@ describe('createAgentChatCompletion - MCP permission user propagation', () => {);});+ it('mirrors the capabilities alone when the embedder wires no role lookup', async () => {+ deps.appConfig = {+ endpoints: { agents: { capabilities: ['file_search'] } },+ } as never;++ await createAgentChatCompletion(createMockReq({ id: 'user-123' }), createMockRes(), deps);++ expect(deps.initializeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ fileSearchAvailable: true, codeEnvAvailable: false }),+ );+ });++ /** One role read answers both grants, so an embedder that wires+ * `getRoleByName` pays for the pairing once and gets each flag separately. */+ it('pairs each capability with its own grant from a single role read', async () => {+ deps.appConfig = {+ endpoints: { agents: { capabilities: ['file_search', 'execute_code'] } },+ } as never;+ const getRoleByName = jest.fn().mockResolvedValue({+ name: 'USER',+ permissions: {+ [PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: false },+ [PermissionTypes.RUN_CODE]: { [Permissions.USE]: true },+ },+ });+ deps.getRoleByName = getRoleByName as never;++ await createAgentChatCompletion(+ createMockReq({ id: 'user-123', role: 'USER' }),+ createMockRes(),+ deps,+ );++ expect(getRoleByName).toHaveBeenCalledTimes(1);+ expect(deps.initializeAgent).toHaveBeenCalledWith(+ expect.objectContaining({ fileSearchAvailable: false, codeEnvAvailable: true }),+ );+ });+it('preserves stateful scope policy status and code in an initialization error response', async () => {const policyError = Object.assign(new Error('Stateful code environment is not allowed by this deployment: conversation'),diff --git a/packages/api/src/agents/openai/service.ts b/packages/api/src/agents/openai/service.tsindex 92243b040c..c03023c4c5 100644--- a/packages/api/src/agents/openai/service.ts+++ b/packages/api/src/agents/openai/service.ts@@ -121,9 +121,10 @@ export interface ChatCompletionDependencies {*/appConfig?: AppConfig;/**- * Supply to have `codeEnvAvailable` respect the caller's `RUN_CODE` grant as- * well as the deployment capability. Optional so existing embedders keep- * their current behavior; without it this route is gated by capability alone.+ * Supply to have `codeEnvAvailable` and `fileSearchAvailable` respect the+ * caller's `RUN_CODE` / `FILE_SEARCH` grants as well as the deployment+ * capabilities. Optional so existing embedders keep their current behavior;+ * without it this route is gated by capability alone.*/getRoleByName?: Parameters<typeof resolveToolRoleGrants>[0]['getRoleByName'];/** Tool execute options for event-driven tool execution */@@ -202,6 +203,13 @@ interface InitializeAgentParams {* skips the expansion (same semantics as the in-repo controllers).*/codeEnvAvailable?: boolean;+ /**+ * Whether `file_search` is available to this caller — the capability AND, when+ * the embedder wires `getRoleByName`, the `FILE_SEARCH` grant. Read only when+ * re-hydrating a conversation's prior-turn files; absent / `undefined` leaves+ * that priming unconditional.+ */+ fileSearchAvailable?: boolean;/*** Whether the admin-level `stateful_code_sessions` capability is enabled.* Threaded to `initializeAgent` alongside `codeEnvAvailable` so this@@ -684,6 +692,14 @@ export async function createAgentChatCompletion(capabilityAllowsCodeEnv === true && deps.getRoleByName != null? (await resolveToolRoleGrants({ req, getRoleByName: deps.getRoleByName })).runCode: capabilityAllowsCodeEnv;+ const capabilityAllowsFileSearch = capabilityEnabled(AgentCapabilities.file_search);+ /** The same pairing for the other gated tool, read only by the resend-file+ * priming inside `initializeAgent`. The grant resolution is memoized on the+ * request, so pairing both flags costs one role read. */+ const fileSearchAvailable =+ capabilityAllowsFileSearch === true && deps.getRoleByName != null+ ? (await resolveToolRoleGrants({ req, getRoleByName: deps.getRoleByName })).fileSearch+ : capabilityAllowsFileSearch;/** Mirror `codeEnvAvailable` for the stateful-session gate so this route* also carries each agent's trusted stateful endpoint/profile selection* into tool loading and prewarming. */@@ -732,6 +748,7 @@ export async function createAgentChatCompletion(allowedProviders,isInitialAgent: true,codeEnvAvailable,+ fileSearchAvailable,statefulSessionsAvailable,allowedStatefulCodeEnvironments,backgroundToolsAvailable,