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: Advertise Stable Uploaded File Paths Before Code Execution (#16578)
Oliver777intd39a7493636e
diff --git a/packages/api/src/agents/__tests__/initialize.test.ts b/packages/api/src/agents/__tests__/initialize.test.tsindex 184868aedd..cab8387219 100644--- a/packages/api/src/agents/__tests__/initialize.test.ts+++ b/packages/api/src/agents/__tests__/initialize.test.ts@@ -4861,6 +4861,107 @@ describe('initializeAgent — authorized run file snapshots', () => {return result;}+ it.each([undefined, 'Extracted document contents'])(+ 'advertises a queued file before tool execution with extracted text %p',+ async (text) => {+ const { agent, req, loadTools, db } = setup();+ if (req.config == null) throw new Error('Missing test configuration');+ req.config.fileConfig = {+ endpoints: {+ [EModelEndpoint.openAI]: {+ defaultLLMDeliveryPath: { overrides: { 'application/pdf': 'text' } },+ },+ },+ };+ loadTools.mockResolvedValue({ toolDefinitions: [{ name: Tools.execute_code }] });+ const file = inputFile({ filename: 'report.pdf', text });+ const result = await initializeAgent(+ {+ req,+ agent,+ loadTools,+ authorizedRunFiles: [file],+ allowedProviders: new Set([Providers.OPENAI]),+ codeEnvAvailable: true,+ },+ db,+ );++ expect(result.dynamicToolContextMap?.queued_code_files).toContain('/mnt/data/report.pdf');+ expect(result.dynamicToolContextMap?.queued_code_files).toContain('read or edit');+ expect(result.dynamicToolContextMap?.queued_code_files).not.toContain(file.filepath);+ expect(result.provisionState?.codeEnvDestinations?.get(file.file_id)).toBe('report.pdf');+ expect(result.provisionState?.codeEnvFiles).toHaveLength(1);+ expect(result.requestAttachments[0].llmDeliveryPath).toBe('text');+ expect(result.requestAttachments[0].text).toBe(text);+ expect(db.getConvoFiles).not.toHaveBeenCalled();+ expect(db.getToolFilesByIds).not.toHaveBeenCalled();+ },+ );++ it('does not advertise code paths when code execution is disabled', async () => {+ const { agent, req, loadTools, db } = setup();+ const result = await initializeAgent(+ {+ req,+ agent,+ loadTools,+ authorizedRunFiles: [inputFile()],+ allowedProviders: new Set([Providers.OPENAI]),+ codeEnvAvailable: false,+ },+ db,+ );+ expect(result.fileConsumers?.executeCode).toBe(false);+ expect(result.dynamicToolContextMap?.queued_code_files).toBeUndefined();+ });++ it.each([undefined, 'Extracted document contents'])(+ 'advertises an earlier upload after code is toggled back on with extracted text %p',+ async (text) => {+ const { agent, req, loadTools, db } = setup();+ agent.tools = [Tools.execute_code];+ const params = {+ req,+ agent,+ loadTools,+ allowedProviders: new Set([Providers.OPENAI]),+ codeEnvAvailable: true,+ };+ await initializeAgent({ ...params, authorizedRunFiles: [] }, db);++ const file = inputFile({ filename: 'report.pdf', text });+ agent.tools = [];+ const disabled = await initializeAgent({ ...params, authorizedRunFiles: [file] }, db);+ expect(disabled.fileConsumers?.executeCode).toBe(false);+ expect(disabled.dynamicToolContextMap?.queued_code_files).toBeUndefined();+ expect(disabled.provisionState?.codeEnvFiles ?? []).toEqual([]);++ agent.tools = [Tools.execute_code];+ (db.getConvoFiles as jest.Mock).mockResolvedValue([file.file_id]);+ (db.getFiles as jest.Mock).mockResolvedValue([file]);+ const getDeferredProvisionFiles = jest.fn().mockResolvedValue([file]);+ const getMessages = jest.fn().mockResolvedValue([{ messageId: 'upload-turn' }]);+ mockGetThreadData.mockReturnValueOnce({ fileIds: [file.file_id] });+ const enabled = await initializeAgent(+ { ...params, conversationId: 'conv-1', parentMessageId: 'upload-turn' },+ { ...db, getMessages, getDeferredProvisionFiles },+ );++ expect(enabled.fileConsumers?.executeCode).toBe(true);+ expect(enabled.requestAttachments).toEqual([]);+ expect(enabled.dynamicToolContextMap?.queued_code_files).toContain('/mnt/data/report.pdf');+ expect(enabled.provisionState?.codeEnvFiles.map((entry) => entry.file_id)).toEqual([+ file.file_id,+ ]);+ expect(getDeferredProvisionFiles).toHaveBeenCalledWith(+ [file.file_id],+ expect.anything(),+ expect.objectContaining({ code: true, hydrateProvisioned: true }),+ );+ },+ );+it('reuses current inputs without reading parent history or counting their usage again', async () => {const { agent, req, loadTools, db } = setup();const file = inputFile();diff --git a/packages/api/src/agents/__tests__/run-codeTools.test.ts b/packages/api/src/agents/__tests__/run-codeTools.test.tsindex 0ab2ee5f46..7602d5c9aa 100644--- a/packages/api/src/agents/__tests__/run-codeTools.test.ts+++ b/packages/api/src/agents/__tests__/run-codeTools.test.ts@@ -1,6 +1,12 @@-import type { SubagentTaskConfig } from '@librechat/agents';+import { FileContext } from 'librechat-data-provider';+import type { AgentInputs, SubagentTaskConfig, SubagentResolveContext } from '@librechat/agents';+import type { TFile } from 'librechat-data-provider';import type { HostSubagentTaskConfig } from '~/agents/subagentDelivery';+import type { ProvisionToolContext } from '~/files/provision/callback';+import type { ServerRequest } from '~/types';+import { createProvisionFilesCallback } from '~/files/provision/callback';import { SUBAGENT_COMPLETION_DELIVERY } from '~/agents/subagentDelivery';+import { mergeCodeFilesIntoContext } from '~/agents/codeFilesSession';import { CHECK_BACKGROUND_TASK_NAME } from '~/agents/background';import { createRun } from '~/agents/run';@@ -102,6 +108,314 @@ async function captureAgentsRunConfig(describe('createRun code-tool eager/session wiring', () => {beforeEach(() => jest.clearAllMocks());+ it('includes queued paths in model instructions and reserves live paths across agents', async () => {+ const file: TFile = {+ file_id: 'uploaded',+ filename: 'data.csv',+ filepath: '/uploads/data.csv',+ type: 'text/csv',+ user: 'user-1',+ object: 'file',+ bytes: 10,+ embedded: false,+ usage: 0,+ context: FileContext.message_attachment,+ };+ const agents = ['a', 'b'].map((id) =>+ makeAgent({+ id,+ fileConsumers: { executeCode: true, fileSearch: false },+ provisionState: {+ codeEnvFiles: [{ ...file }],+ vectorDBFiles: [],+ aliveFileIds: new Set(),+ agentScopedFileIds: new Set(),+ },+ dynamicToolContextMap: { execute_code: 'Previously primed file context' },+ additional_instructions: 'Agent instructions',+ tool_resources:+ id === 'a' ? { execute_code: { files: [{ ...file, file_id: 'existing' }] } } : undefined,+ }),+ );+ const config = await captureAgentsRunConfig(agents);+ const inputs = (config.graphConfig as { agents: Array<{ additional_instructions: string }> })+ .agents;+ const paths = inputs.map(+ (input) => input.additional_instructions.match(/\/mnt\/data\/\S+/)?.[0],+ );++ expect(paths[0]).toBeDefined();+ expect(paths[0]).not.toBe('/mnt/data/data.csv');+ expect(paths[1]).toBe(paths[0]);+ for (const input of inputs) {+ expect(input.additional_instructions).toContain('Previously primed file context');+ expect(input.additional_instructions).toContain('Agent instructions');+ expect(input.additional_instructions).toContain('read or edit');+ expect(input.additional_instructions).not.toContain(file.filepath);+ }+ });++ it('preserves parent paths when a lazy child has independently planned colliding files', async () => {+ const shared: TFile = {+ file_id: 'shared',+ filename: 'data.csv',+ filepath: '/uploads/data.csv',+ type: 'text/csv',+ user: 'user-1',+ object: 'file',+ bytes: 10,+ embedded: false,+ usage: 0,+ context: FileContext.message_attachment,+ createdAt: '2026-09-01',+ };+ const child = makeAgent({+ id: 'child',+ fileConsumers: { executeCode: true, fileSearch: false },+ provisionState: {+ codeEnvFiles: [{ ...shared }, { ...shared, file_id: 'new', createdAt: '2026-10-01' }],+ vectorDBFiles: [],+ aliveFileIds: new Set(),+ agentScopedFileIds: new Set(),+ codeEnvDestinations: new Map([+ ['shared', 'draft-alias.csv'],+ ['new', 'data.csv'],+ ]),+ },+ });+ const resolve = jest.fn().mockResolvedValue(child);+ const config = await captureRunConfig(+ makeAgent({+ fileConsumers: { executeCode: true, fileSearch: false },+ provisionState: {+ codeEnvFiles: [{ ...shared }],+ vectorDBFiles: [],+ aliveFileIds: new Set(),+ agentScopedFileIds: new Set(),+ },+ subagents: { enabled: true, allowSelf: false, agent_ids: ['child'] },+ lazySubagentConfigs: [{ id: 'child', configId: 'child:1', resolve }],+ }),+ );+ const [parentInput] = (config.graphConfig as { agents: AgentInputs[] }).agents;+ expect(parentInput.additional_instructions).toContain('/mnt/data/data.csv');+ expect(resolve).not.toHaveBeenCalled();+ const lazyConfig = parentInput.subagentConfigs?.[0];+ const resolveInputs = lazyConfig?.resolveAgentInputs;+ if (!resolveInputs) throw new Error('Missing lazy subagent resolver');+ const childInput = await resolveInputs({+ signal: new AbortController().signal,+ } as SubagentResolveContext);+ expect(childInput.additional_instructions).toContain('/mnt/data/data.csv');+ expect(childInput.additional_instructions).not.toContain('draft-alias.csv');+ expect(childInput.additional_instructions?.match(/\/mnt\/data\/data\.csv/g)).toHaveLength(1);+ });++ it.each([false, true])(+ 'reconciles a lazy child’s live setup file, parent already provisioned=%s',+ async (parentProvisioned) => {+ const shared: TFile = {+ file_id: 'shared',+ filename: 'data.csv',+ filepath: '/uploads/data.csv',+ type: 'text/csv',+ user: 'user-1',+ object: 'file',+ bytes: 10,+ embedded: false,+ usage: 0,+ context: FileContext.message_attachment,+ };+ const live = {+ id: 'setup-remote',+ name: 'data.csv',+ storage_session_id: 'setup-store',+ resource_id: 'child',+ kind: 'agent' as const,+ };+ const child = {+ ...makeAgent({+ id: 'child',+ primedCodeFiles: [live],+ fileConsumers: { executeCode: true, fileSearch: false },+ tool_resources: { execute_code: { files: [{ ...shared, file_id: 'setup' }] } },+ }),+ provisionState: {+ codeEnvFiles: [{ ...shared }],+ vectorDBFiles: [],+ aliveFileIds: new Set(['setup']),+ agentScopedFileIds: new Set(['setup']),+ codeEnvDestinations: new Map([['shared', 'safe-child-alias.csv']]),+ },+ };+ const resolve = jest.fn().mockResolvedValue(child);+ const provisionState = {+ codeEnvFiles: [{ ...shared }],+ vectorDBFiles: [],+ aliveFileIds: new Set(),+ agentScopedFileIds: new Set(),+ };+ const toolResources = { execute_code: { files: [] as TFile[] } };+ const config = await captureRunConfig(+ makeAgent({+ fileConsumers: { executeCode: true, fileSearch: false },+ provisionState,+ tool_resources: toolResources,+ subagents: { enabled: true, allowSelf: false, agent_ids: ['child'] },+ lazySubagentConfigs: [{ id: 'child', configId: 'child:1', resolve }],+ }),+ );+ const [parentInput] = (config.graphConfig as { agents: AgentInputs[] }).agents;+ expect(parentInput.additional_instructions).toContain('/mnt/data/data.csv');+ expect(resolve).not.toHaveBeenCalled();+ if (parentProvisioned) {+ provisionState.codeEnvFiles = [];+ toolResources.execute_code.files.push({ ...shared });+ }+ const resolveInputs = parentInput.subagentConfigs?.[0].resolveAgentInputs;+ if (!resolveInputs) throw new Error('Missing lazy subagent resolver');+ const childInput = await resolveInputs({+ signal: new AbortController().signal,+ } as SubagentResolveContext);+ const childPath = child.provisionState?.codeEnvDestinations?.get(shared.file_id);+ expect(childPath).toBeDefined();+ expect(childPath).not.toBe('data.csv');+ expect(childInput.additional_instructions).toContain(`/mnt/data/${childPath}`);+ expect(parentInput.additional_instructions).toContain('/mnt/data/data.csv');+ expect(childInput.initialSessions?.get('execute_code')?.files).toEqual([live]);+ },+ );++ it.each(+ [+ ['data.csv', 'data.csv'],+ ['data', 'data/input.csv'],+ ['data/input.csv', 'data'],+ ].flatMap(([parentName, childName]) =>+ ['sequential', 'parallel'].map((mode) => ({ parentName, childName, mode })),+ ),+ )(+ 'reconciles repeated $mode lazy instances against $parentName while uploading $childName',+ async ({ mode, parentName, childName }) => {+ const parentFile: TFile = {+ file_id: 'parent-file',+ filename: parentName,+ filepath: '/uploads/data.csv',+ type: 'text/csv',+ user: 'user-1',+ object: 'file',+ bytes: 10,+ embedded: false,+ usage: 0,+ context: FileContext.message_attachment,+ };+ const childFile = {+ ...parentFile,+ file_id: 'child-file',+ filename: childName,+ context: FileContext.agents,+ };+ const makeChild = () => ({+ ...makeAgent({ id: 'child' }),+ fileConsumers: { executeCode: true, fileSearch: false },+ dynamicToolContextMap: {},+ provisionState: {+ codeEnvFiles: [{ ...childFile }],+ vectorDBFiles: [],+ aliveFileIds: new Set<string>(),+ agentScopedFileIds: new Set([childFile.file_id]),+ codeEnvDestinations: new Map([[childFile.file_id, childFile.filename]]),+ },+ });+ const children = [makeChild(), makeChild()];+ const resolve = jest+ .fn()+ .mockResolvedValueOnce(children[0])+ .mockResolvedValueOnce(children[1]);+ const parent = {+ ...makeAgent(),+ tool_resources: { execute_code: { files: [parentFile] } },+ subagents: { enabled: true, allowSelf: false, agent_ids: ['child'] },+ lazySubagentConfigs: [{ id: 'child', configId: 'child:1', resolve }],+ };+ const config = await captureRunConfig(parent);+ const [parentInput] = (config.graphConfig as { agents: AgentInputs[] }).agents;+ const resolveInputs = parentInput.subagentConfigs?.[0].resolveAgentInputs;+ if (!resolveInputs) throw new Error('Missing lazy subagent resolver');+ const resolutionContext = {+ signal: new AbortController().signal,+ } as SubagentResolveContext;+ const inputs =+ mode === 'parallel'+ ? await Promise.all(children.map(() => resolveInputs(resolutionContext)))+ : [await resolveInputs(resolutionContext), await resolveInputs(resolutionContext)];+ const names = children.map((child) =>+ child.provisionState.codeEnvDestinations.get(childFile.file_id),+ );+ for (let index = 0; index < children.length; index++) {+ expect(names[index]).toBeDefined();+ expect(names[index]).not.toBe(childFile.filename);+ expect(inputs[index].additional_instructions).toContain(`/mnt/data/${names[index]}`);+ }+ expect(names[1]).toBe(names[0]);+ expect(children[0].provisionState.codeEnvDestinations).not.toBe(+ children[1].provisionState.codeEnvDestinations,+ );++ const contexts = new Map<string, ProvisionToolContext>([[parent.id, parent]]);+ const provisionToCodeEnv = jest.fn(+ async ({ file, sandboxFilename }: { file: TFile; sandboxFilename?: string }) => {+ const ref = {+ kind: 'agent' as const,+ id: 'child',+ storage_session_id: 'child-store',+ file_id: file.file_id,+ sandboxFilename,+ };+ return {+ referenceSet: { codeEnvRefs: { default: ref } },+ refUpdate: { file_id: file.file_id, routeKey: 'default', ref },+ sandboxFilename: sandboxFilename ?? file.filename,+ };+ },+ );+ const provision = createProvisionFilesCallback({+ req: { user: { id: 'user-1' } } as ServerRequest,+ agentToolContexts: contexts,+ provisionToCodeEnv,+ provisionToVectorDB: jest.fn(),+ updateFile: jest.fn(),+ updateCodeEnvRef: jest.fn(),+ addEmbeddedEntity: jest.fn(),+ });+ for (const child of children) {+ contexts.set(child.id, child);+ const refs = await provision(['execute_code'], child.id);+ const merged = mergeCodeFilesIntoContext(+ {+ session_id: 'parent-store',+ files: [+ {+ id: parentFile.file_id,+ storage_session_id: 'parent-store',+ name: parentFile.filename,+ resource_id: 'user-1',+ kind: 'user',+ },+ ],+ },+ refs,+ );+ expect(merged?.files.map((file) => file.name)).toEqual([parentFile.filename, names[0]]);+ }+ expect(provisionToCodeEnv).toHaveBeenCalledTimes(1);+ const earlierPlan = children[0].provisionState.codeEnvDestinations;+ resolve.mockResolvedValueOnce(children[0]);+ await resolveInputs(resolutionContext);+ expect(children[0].provisionState.codeEnvDestinations).toBe(earlierPlan);+ },+ );+it('excludes side-effecting/large-arg tools from eager execution', async () => {const runConfig = await captureRunConfig();const eager = runConfig.eagerEventToolExecution as {diff --git a/packages/api/src/agents/files/host.spec.ts b/packages/api/src/agents/files/host.spec.tsindex c557cb5340..46c1d631af 100644--- a/packages/api/src/agents/files/host.spec.ts+++ b/packages/api/src/agents/files/host.spec.ts@@ -387,6 +387,47 @@ describe('run file execution host', () => {).toEqual(['historical']);});+ it('retains only admitted advertised paths when preparing isolated child queues', async () => {+ const current = file('input', { filename: 'data.csv' });+ const h = harness({ inputs: [current] });+ const source = h.contexts.get('worker')!;+ source.provisionState = {+ codeEnvFiles: [current],+ vectorDBFiles: [],+ aliveFileIds: new Set(),+ agentScopedFileIds: new Set(['worker-setup']),+ codeEnvDestinations: new Map([+ ['input', 'data-shared.csv'],+ ['worker-setup', 'setup-advertised.csv'],+ ['historical', 'private-history.csv'],+ ]),+ };+ const executions = [identity('first'), identity('second')];+ await Promise.all(executions.map((execution) => h.prepare(execution)));+ for (const execution of executions) {+ const destinations = h.host.getContext('worker', execution)?.provisionState+ ?.codeEnvDestinations;+ expect(destinations).toEqual(+ new Map([+ ['input', 'data-shared.csv'],+ ['worker-setup', 'setup-advertised.csv'],+ ]),+ );+ expect(destinations).not.toBe(source.provisionState.codeEnvDestinations);+ await h.host.provision([Constants.EXECUTE_CODE], 'worker', h.signal, execution);+ }+ expect(h.provisionToCodeEnv).toHaveBeenCalledTimes(4);+ for (const [params] of h.provisionToCodeEnv.mock.calls) {+ expect(params.sandboxFilename).toBe(+ source.provisionState.codeEnvDestinations?.get(params.file.file_id),+ );+ }+ expect(source.provisionState.codeEnvDestinations?.has('historical')).toBe(true);+ expect(+ h.host.getContext('worker', executions[0])?.provisionState?.codeEnvDestinations,+ ).not.toBe(h.host.getContext('worker', executions[1])?.provisionState?.codeEnvDestinations);+ });+it('isolates concurrent executions of the same agent without broadening storage grants', async () => {const h = harness();const first = identity('first');diff --git a/packages/api/src/agents/files/host.ts b/packages/api/src/agents/files/host.tsindex c0f187fc8e..b1b140e254 100644--- a/packages/api/src/agents/files/host.ts+++ b/packages/api/src/agents/files/host.ts@@ -418,7 +418,19 @@ export function createRunFileHost<TContext extends RunFileToolContext>({codeEnvRecoveryNames: undefined,}: undefined);- if (provisionState) provisionState.agentScopedFileIds = admittedSetupIds;+ if (provisionState) {+ provisionState.agentScopedFileIds = admittedSetupIds;+ const destinations = new Map<string, string>();+ for (const planned of [+ source.provisionState?.codeEnvDestinations,+ existingContext?.provisionState?.codeEnvDestinations,+ ]) {+ for (const [fileId, destination] of planned ?? []) {+ if (admittedIds.has(fileId)) destinations.set(fileId, destination);+ }+ }+ provisionState.codeEnvDestinations = destinations;+ }const context: TContext = existingContext ?? {...source,pendingProvisionedCodeFiles: undefined,diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.tsindex 1fc8862453..4ee56c8f96 100644--- a/packages/api/src/agents/initialize.ts+++ b/packages/api/src/agents/initialize.ts@@ -131,6 +131,7 @@ import { isImplicitStatefulCodeRouteAvailable } from '../code/config';import { PARTIAL_RESOLVED_CONVERSATION } from './conversationSymbols';import { registerMemoryTools, memoryToolUsageGuard } from './memory';import { applyIntentLabels, sanitizeIntentLabels } from './intent';+import { prepareQueuedCodeFileContext } from '~/files/code/queued';import { ContentFilterError } from '../middleware/contentFilter';import { resolveToolRoleGrants } from '~/tools/rolePermissions';import { createRequestAgentExecutionContext } from './runtime';@@ -2740,5 +2741,13 @@ export async function initializeAgent(endpointTokenConfig: options.endpointTokenConfig,};+ prepareQueuedCodeFileContext(initializedAgent, [initializedAgent], user?.id);+ const queuedFileContext = initializedAgent.dynamicToolContextMap?.queued_code_files;+ if (typeof queuedFileContext === 'string') {+ assertModelBoundContent({+ filters: appConfig?.filters,+ files: [{ content: queuedFileContext }],+ });+ }return initializedAgent;}diff --git a/packages/api/src/agents/resources.ts b/packages/api/src/agents/resources.tsindex 394e564a84..e312a5d767 100644--- a/packages/api/src/agents/resources.ts+++ b/packages/api/src/agents/resources.ts@@ -90,6 +90,8 @@ export type ProvisionState = {codeEnvFiles: TFile[];/** Names from cleared refs on this state's active route; never reusable storage pointers. */codeEnvRecoveryNames?: Map<string, { name: string; isTargetScope: boolean }>;+ /** Destination names advertised to the model before lazy code-file provisioning. */+ codeEnvDestinations?: Map<string, string>;/** Files that need embedding into the vector DB for file_search */vectorDBFiles: TFile[];/** Set of file_ids confirmed alive in code env (from staleness check) */diff --git a/packages/api/src/agents/run.ts b/packages/api/src/agents/run.tsindex 0d0a97864e..848c35019c 100644--- a/packages/api/src/agents/run.ts+++ b/packages/api/src/agents/run.ts@@ -46,6 +46,7 @@ import type {AgentSubagentGraph,ReasoningResponseKey,SummarizationConfig,+ TurnFileConsumers,} from 'librechat-data-provider';import type { AppConfig, IAgentFadingTier, IUser } from '@librechat/data-schemas';import type { CallbackHandlerMethods } from '@langchain/core/callbacks/base';@@ -61,6 +62,7 @@ import type { ResolvedAlwaysApplySkill } from '~/agents/skills';import type { CodeExecutionContext } from '~/agents/execution';import type { MCPToolAlias } from '~/tools/classification';import type { SubagentUsageEvent } from '~/agents/usage';+import type { ProvisionState } from '~/agents/resources';import type { RunFileSession } from './files/session';import type { RunFadingTiers } from './fading';import type * as t from '~/types';@@ -117,6 +119,7 @@ import { CREATE_FILE_TOOL_NAME, EDIT_FILE_TOOL_NAME } from '~/agents/tools';import { buildAgentInitialToolSessions } from '~/agents/codeFilesSession';import { getDirectDispatcher, getProxyDispatcher } from '~/utils/proxy';import { getAzureCredentials, constructAzureURL } from '~/utils/azure';+import { prepareQueuedCodeFileContext } from '~/files/code/queued';import { getBuiltInBaseURL } from '~/endpoints/openai/initialize';import { getProviderConfig } from '~/endpoints/config/providers';import { buildToolApprovalHooks } from '~/agents/hitl/hooks';@@ -419,6 +422,8 @@ export function shouldReplayReasoningContent(}type RunAgent = Omit<Agent, 'tools'> & {+ provisionState?: ProvisionState;+ fileConsumers?: TurnFileConsumers;azureOptions?: t.AzureOptions;tools?: GenericTool[];maxContextTokens?: number;@@ -2319,7 +2324,29 @@ export async function createRun({/** Admin kill switch for the ask tool — see {@link isAskUserQuestionAdminDisabled}. */const askToolAdminDisabled = isAskUserQuestionAdminDisabled(appConfig);+ // Independently initialized agents must reserve the same live paths before advertising uploads.+ const codeFileAgents = new Map<string, RunAgent>();+ const visitedCodeFileAgents = new Set<string>();+ const pendingCodeFileAgents: Array<RunAgent | null | undefined> = [...agents];+ for (let index = 0; index < pendingCodeFileAgents.length; index++) {+ const agent = pendingCodeFileAgents[index];+ if (!agent?.id || codeFileAgents.has(agent.id)) continue;+ codeFileAgents.set(agent.id, agent);+ visitedCodeFileAgents.add(agent.id);+ enqueueSubagentChildren(agent, pendingCodeFileAgents, visitedCodeFileAgents, false, false);+ }+ for (const agent of codeFileAgents.values()) {+ prepareQueuedCodeFileContext(agent, codeFileAgents.values(), user?.id);+ }++ const preparedCodeFileAgents = new WeakSet(codeFileAgents.values());const buildAgentInput = (agent: RunAgent, opts: { isSubagent?: boolean } = {}): AgentInputs => {+ if (!preparedCodeFileAgents.has(agent)) {+ if (agent.provisionState) agent.provisionState.codeEnvDestinations = undefined;+ codeFileAgents.set(agent.id, agent);+ prepareQueuedCodeFileContext(agent, codeFileAgents.values(), user?.id, true);+ preparedCodeFileAgents.add(agent);+ }const isSubagent = opts.isSubagent === true;if (runFilesActive) {for (const { memberConfigs } of agent.subagentGraphConfigs ?? []) {diff --git a/packages/api/src/files/code/queued.spec.ts b/packages/api/src/files/code/queued.spec.tsnew file mode 100644index 0000000000..94db4e890d--- /dev/null+++ b/packages/api/src/files/code/queued.spec.ts@@ -0,0 +1,104 @@+import { FileContext } from 'librechat-data-provider';+import type { TFile } from 'librechat-data-provider';+import type { CodeFileAgent } from './queued';+import { planCodeFileUploads, prepareQueuedCodeFileContext } from './queued';++function file(id: string, overrides: Partial<TFile> = {}): TFile {+ return {+ file_id: id,+ filename: 'data.csv',+ filepath: '/uploads/data.csv',+ type: 'text/csv',+ user: 'user-1',+ object: 'file',+ bytes: 10,+ embedded: false,+ usage: 0,+ context: FileContext.message_attachment,+ ...overrides,+ };+}++function agent(id: string, files: TFile[]): CodeFileAgent {+ return {+ id,+ fileConsumers: { executeCode: true, fileSearch: false },+ provisionState: {+ codeEnvFiles: files,+ vectorDBFiles: [],+ aliveFileIds: new Set(),+ agentScopedFileIds: new Set(),+ },+ dynamicToolContextMap: {},+ };+}++describe('queued code-file destinations', () => {+ it('keeps an advertised shared path when a lazy agent adds a newer colliding input', () => {+ const shared = file('shared', { createdAt: '2026-09-01' });+ const parent = agent('parent', [{ ...shared }]);+ prepareQueuedCodeFileContext(parent, [parent], 'user-1');+ const advertised = parent.provisionState?.codeEnvDestinations?.get('shared');+ const child = agent('child', [{ ...shared }, file('new', { createdAt: '2026-10-01' })]);+ prepareQueuedCodeFileContext(child, [parent, child], 'user-1', true);++ expect(child.provisionState?.codeEnvDestinations?.get('shared')).toBe(advertised);+ expect(child.provisionState?.codeEnvDestinations?.get('new')).not.toBe(advertised);+ expect(+ planCodeFileUploads({+ context: child,+ contexts: [parent, child],+ agentId: child.id,+ userId: 'user-1',+ useAdvertisedNames: true,+ }).find((upload) => upload.file.file_id === 'shared')?.destination,+ ).toBe(advertised);+ });++ it('does not move a confirmed live path when another agent also queues that file', () => {+ const shared = file('shared', {+ createdAt: '2026-09-01',+ metadata: {+ codeEnvRefs: {+ default: {+ kind: 'user',+ id: 'user-1',+ storage_session_id: 'session',+ file_id: 'remote',+ sandboxFilename: 'data.csv',+ },+ },+ },+ });+ const parent = agent('parent', [file('new', { createdAt: '2026-10-01' })]);+ parent.tool_resources = { execute_code: { files: [shared] } };+ const child = agent('child', [{ ...shared }, file('new', { createdAt: '2026-10-01' })]);+ for (const current of [parent, child]) {+ prepareQueuedCodeFileContext(current, [parent, child], 'user-1');+ }++ expect(parent.provisionState?.codeEnvDestinations?.get('new')).not.toBe('data.csv');+ expect(child.provisionState?.codeEnvDestinations?.get('shared')).toBe('data.csv');+ });++ it('retains advertised paths after one file succeeds and another remains queued', () => {+ const current = agent('parent', [file('first'), file('second')]);+ prepareQueuedCodeFileContext(current, [current], 'user-1');+ const advertised = new Map(current.provisionState?.codeEnvDestinations);+ current.provisionState!.codeEnvFiles = [file('second')];+ current.pendingProvisionedCodeFiles = [+ {+ id: 'remote-first',+ name: advertised.get('first')!,+ storage_session_id: 'session',+ resource_id: 'user-1',+ kind: 'user',+ },+ ];+ prepareQueuedCodeFileContext(current, [current], 'user-1');++ expect(current.provisionState?.codeEnvDestinations?.get('second')).toBe(+ advertised.get('second'),+ );+ });+});diff --git a/packages/api/src/files/code/queued.ts b/packages/api/src/files/code/queued.tsnew file mode 100644index 0000000000..39a497f6d9--- /dev/null+++ b/packages/api/src/files/code/queued.ts@@ -0,0 +1,209 @@+import { getCodeEnvRefForProfile, resolveSandboxFilename } from 'librechat-data-provider';+import type { TFile, TurnFileConsumers, AgentToolResources } from 'librechat-data-provider';+import type { CodeEnvFile } from '@librechat/agents';+import type { CodeExecutionRoute } from '../provision/service';+import type { CodeExecutionContext } from '~/agents/execution';+import type { ProvisionState } from '~/agents/resources';+import {+ claimCodeDestination,+ createCodeDestinationSet,+ reserveCodeDestination,+ sortCodeFilesByDestinationPriority,+} from './destinations';+import { appendCodeFileContextLine, getCodeFileContextLine, getCodeFileLocation } from './priming';+import { getCodeEnvUploadFilename } from './form';++/** Shared file state used by prompt construction and lazy provisioning. */+export interface ProvisionToolContext {+ provisionState?: ProvisionState;+ tool_resources?: AgentToolResources;+ /** Code API deployment this agent resolved, so uploads land where it will execute. */+ codeExecutionContext?: CodeExecutionRoute;+ /** Successful refs retained while another file in the same batch awaits retry. */+ pendingProvisionedCodeFiles?: CodeEnvFile[];+}++export interface CodeFileAgent extends ProvisionToolContext {+ id: string;+ fileConsumers?: TurnFileConsumers;+ codeExecutionContext?: CodeExecutionContext;+ dynamicToolContextMap?: Record<string, unknown>;+}++interface CodeFileUpload {+ file: TFile;+ destination: string;+}++function routeKey(context: ProvisionToolContext): string {+ return (+ context.codeExecutionContext?.executionRouteKey ??+ context.codeExecutionContext?.executionProfile ??+ 'default'+ );+}++/** Uses the same destination plan before inference and when files are uploaded lazily. */+export function planCodeFileUploads({+ context,+ contexts,+ agentId,+ userId,+ useAdvertisedNames = false,+}: {+ context: ProvisionToolContext;+ contexts: Iterable<ProvisionToolContext>;+ agentId?: string;+ userId?: string;+ useAdvertisedNames?: boolean;+}): CodeFileUpload[] {+ const state = context.provisionState;+ if (!state?.codeEnvFiles.length) return [];+ const route = routeKey(context);+ const routeContexts = [...contexts].filter((candidate) => routeKey(candidate) === route);+ if (!routeContexts.includes(context)) routeContexts.push(context);+ const queuedIds = new Set(state.codeEnvFiles.map((file) => file.file_id));+ const liveFiles = context.tool_resources?.execute_code?.files ?? [];+ const privateIds = new Set<string>();+ const queued = new Map<string, { file: TFile; recoveryName?: string; advertisedName?: string }>();+ for (const candidate of routeContexts) {+ for (const id of candidate.provisionState?.agentScopedFileIds ?? []) privateIds.add(id);+ for (const file of candidate.provisionState?.codeEnvFiles ?? []) {+ if (queued.has(file.file_id)) continue;+ queued.set(file.file_id, {+ file,+ recoveryName: candidate.provisionState?.codeEnvRecoveryNames?.get(file.file_id)?.name,+ advertisedName: candidate.provisionState?.codeEnvDestinations?.get(file.file_id),+ });+ }+ }++ const confirmedNames = new Set<string>();+ const files = sortCodeFilesByDestinationPriority(+ [...state.codeEnvFiles, ...liveFiles.filter((file) => !queuedIds.has(file.file_id))],+ privateIds,+ ).filter((file): file is TFile => {+ if (!file) return false;+ const ref = getCodeEnvRefForProfile(file.metadata, route);+ const recovery = state.codeEnvRecoveryNames?.get(file.file_id);+ const entityId = state.agentScopedFileIds.has(file.file_id) ? agentId : undefined;+ const isTargetScope =+ ref != null && ref.kind === (entityId ? 'agent' : 'user') && ref.id === (entityId ?? userId);+ let storedName = recovery?.isTargetScope ? recovery.name : undefined;+ if (isTargetScope) storedName = ref?.sandboxFilename;+ // Equal stored paths identify superseded content; prefix conflicts remain separate inputs.+ if (storedName == null) return true;+ if (confirmedNames.has(storedName)) return false;+ confirmedNames.add(storedName);+ return true;+ });++ const destinations = createCodeDestinationSet();+ const liveNames = new Map<string, string>();+ const reserveLiveFiles = (candidate: ProvisionToolContext): void => {+ const candidateQueuedIds = new Set(+ candidate.provisionState?.codeEnvFiles.map((file) => file.file_id),+ );+ for (const file of candidate.tool_resources?.execute_code?.files ?? []) {+ if (candidateQueuedIds.has(file.file_id)) continue;+ const name =+ getCodeEnvRefForProfile(file.metadata, route)?.sandboxFilename ??+ candidate.provisionState?.codeEnvDestinations?.get(file.file_id) ??+ resolveSandboxFilename(file.filename, file.type);+ if (reserveCodeDestination(destinations, name) && !liveNames.has(file.file_id)) {+ liveNames.set(file.file_id, name);+ }+ }+ };+ // Foreign live paths can be reused only after this agent's immutable mounts claim theirs.+ reserveLiveFiles(context);+ for (const candidate of routeContexts) {+ if (candidate !== context) reserveLiveFiles(candidate);+ }+ for (const file of context.pendingProvisionedCodeFiles ?? []) {+ claimCodeDestination(destinations, file.name, file.id);+ }++ const queuedFiles = files.filter((file) => queuedIds.has(file.file_id));+ const selected = new Map(queuedFiles.map((file) => [file.file_id, file]));+ const advertisedNames = new Map<string, string>();+ if (useAdvertisedNames) {+ // An agent's frozen plan survives later discovery in other execution contexts.+ for (const [id, name] of state.codeEnvDestinations ?? []) {+ if (!queued.has(id)) continue;+ reserveCodeDestination(destinations, name);+ advertisedNames.set(id, name);+ }+ // Inherited paths are hints until checked against this agent's live mounts.+ for (const [id, candidate] of queued) {+ if (advertisedNames.has(id) || liveNames.has(id)) continue;+ const name = candidate.advertisedName;+ if (name != null && reserveCodeDestination(destinations, name)) {+ advertisedNames.set(id, name);+ }+ }+ }+ const uploads: CodeFileUpload[] = [];+ // Assign across the route's queued inputs, but expose only this agent's selected files.+ for (const file of sortCodeFilesByDestinationPriority(+ [...queued.values()].map((candidate) => candidate.file),+ privateIds,+ )) {+ if (!file) continue;+ const candidate = queued.get(file.file_id);+ const destination =+ advertisedNames.get(file.file_id) ??+ liveNames.get(file.file_id) ??+ claimCodeDestination(+ destinations,+ getCodeEnvUploadFilename(+ resolveSandboxFilename(+ getCodeEnvRefForProfile(file.metadata, route)?.sandboxFilename ??+ candidate?.recoveryName ??+ file.filename,+ file.type,+ ),+ ),+ file.file_id,+ );+ const selectedFile = selected.get(file.file_id);+ if (selectedFile) uploads.push({ file: selectedFile, destination });+ }+ return uploads;+}++/** Adds metadata independently of extracted text, using only already-authorized file queues. */+export function prepareQueuedCodeFileContext(+ agent: CodeFileAgent,+ contexts: Iterable<ProvisionToolContext>,+ userId?: string,+ useAdvertisedNames = false,+): void {+ const key = 'queued_code_files';+ if (agent.dynamicToolContextMap) delete agent.dynamicToolContextMap[key];+ if (agent.fileConsumers?.executeCode !== true || !agent.provisionState) return;+ const uploads = planCodeFileUploads({+ context: agent,+ contexts,+ agentId: agent.id,+ userId,+ useAdvertisedNames,+ });+ agent.provisionState.codeEnvDestinations = new Map(+ uploads.map(({ file, destination }) => [file.file_id, destination]),+ );+ const location = getCodeFileLocation(agent.codeExecutionContext);+ let context = '';+ for (const { file, destination } of uploads) {+ context = appendCodeFileContextLine(+ context,+ getCodeFileContextLine(file, agent.provisionState.agentScopedFileIds, destination, location),+ location,+ );+ }+ if (!context) return;+ agent.dynamicToolContextMap ??= {};+ agent.dynamicToolContextMap[key] =+ `${context}\nFiles are staged at these paths on demand for code execution. ` ++ 'You can read or edit them even when their extracted text is already in context.';+}diff --git a/packages/api/src/files/provision/callback.spec.ts b/packages/api/src/files/provision/callback.spec.tsindex 8408215bce..18662f5573 100644--- a/packages/api/src/files/provision/callback.spec.ts+++ b/packages/api/src/files/provision/callback.spec.ts@@ -3,7 +3,10 @@ import { EToolResources, FileContext } from 'librechat-data-provider';import type { TFile } from 'librechat-data-provider';import type { ProvisionState } from '~/agents/resources';import type { ProvisionToolContext } from './callback';+import type { CodeFileAgent } from '../code/queued';import type { ServerRequest } from '~/types';+import { mergeCodeFilesIntoContext } from '~/agents/codeFilesSession';+import { prepareQueuedCodeFileContext } from '../code/queued';import { createProvisionFilesCallback } from './callback';jest.mock('@librechat/data-schemas', () => ({@@ -103,6 +106,201 @@ function buildHarness({}describe('createProvisionFilesCallback', () => {+ it.each(['a', 'b'])(+ 'keeps distinct queued files reachable at their advertised paths when %s runs first',+ async (firstAgentId) => {+ const agents = ['a', 'b'].map((id) => {+ const dynamicToolContextMap: Record<string, unknown> = {};+ return {+ id,+ provisionState: state([makeFile({ file_id: id, context: FileContext.agents })], [], [id]),+ fileConsumers: { executeCode: true, fileSearch: false },+ dynamicToolContextMap,+ };+ });+ for (const agent of agents) prepareQueuedCodeFileContext(agent, agents, req.user?.id);+ const names = agents.map((agent) => agent.provisionState.codeEnvDestinations?.get(agent.id));+ expect(new Set(names).size).toBe(2);+ for (const [index, agent] of agents.entries()) {+ const paths = String(agent.dynamicToolContextMap.queued_code_files)+ .split('\n')+ .filter((line) => line.includes('/mnt/data/'));+ expect(paths).toHaveLength(1);+ expect(paths[0]).toContain(`/mnt/data/${names[index]}`);+ }++ const { provisionFiles, provisionToCodeEnv } = buildHarness({+ contexts: agents.map((agent) => [agent.id, agent]),+ });+ await provisionFiles([Constants.EXECUTE_CODE], firstAgentId);+ await provisionFiles([Constants.EXECUTE_CODE], firstAgentId === 'a' ? 'b' : 'a');+ for (const [args] of provisionToCodeEnv.mock.calls) {+ const agent = agents.find((candidate) => candidate.id === args.file.file_id);+ expect(args.sandboxFilename).toBe(agent?.provisionState.codeEnvDestinations?.get(agent.id));+ }+ },+ );++ it.each(+ [+ ['data.csv', 'data.csv'],+ ['data', 'data/input.csv'],+ ['data/input.csv', 'data'],+ ].flatMap(([liveName, uploadName]) =>+ ['parent', 'child'].flatMap((firstAgentId) =>+ [false, true].flatMap((retry) =>+ [false, true].map((parentProvisioned) => ({+ firstAgentId,+ liveName,+ uploadName,+ retry,+ parentProvisioned,+ })),+ ),+ ),+ ),+ )(+ 'keeps $firstAgentId-first mounts ($liveName) and uploads ($uploadName), retry=$retry, parentProvisioned=$parentProvisioned',+ async ({ firstAgentId, liveName, uploadName, retry, parentProvisioned }) => {+ const shared = makeFile({ file_id: 'shared', filename: uploadName });+ const parent: CodeFileAgent = {+ id: 'parent',+ fileConsumers: { executeCode: true, fileSearch: false },+ provisionState: state([{ ...shared }], []),+ };+ prepareQueuedCodeFileContext(parent, [parent], req.user?.id);+ const parentPath = parent.provisionState?.codeEnvDestinations?.get(shared.file_id);+ const live = makeFile({+ file_id: 'setup',+ filename: liveName,+ context: FileContext.agents,+ metadata: {+ codeEnvRefs: {+ default: {+ kind: 'agent',+ id: 'child',+ storage_session_id: 'setup-store',+ file_id: 'setup-remote',+ sandboxFilename: liveName,+ },+ },+ },+ });+ const child: CodeFileAgent = {+ id: 'child',+ fileConsumers: { executeCode: true, fileSearch: false },+ provisionState: state([{ ...shared }], [], [live.file_id]),+ tool_resources: { execute_code: { files: [live] } },+ };+ const { provisionFiles, provisionToCodeEnv, agentToolContexts } = buildHarness({+ contexts: [[parent.id, parent]],+ });+ const provisioned = new Map<string, Awaited<ReturnType<typeof provisionFiles>>>();+ if (parentProvisioned) {+ provisioned.set(parent.id, await provisionFiles([Constants.EXECUTE_CODE], parent.id));+ expect(child.provisionState?.codeEnvFiles[0].metadata?.codeEnvRefs).toBeUndefined();+ }+ agentToolContexts.set(child.id, child);+ prepareQueuedCodeFileContext(child, [parent, child], req.user?.id, true);+ const childPath = child.provisionState?.codeEnvDestinations?.get(shared.file_id);+ expect(childPath).toBeDefined();+ expect(childPath).not.toBe(parentPath);+ expect(child.dynamicToolContextMap?.queued_code_files).toContain(`/mnt/data/${childPath}`);++ if (retry) provisionToCodeEnv.mockRejectedValueOnce(new Error('Transient upload failure'));+ const order = parentProvisioned+ ? [child.id]+ : [firstAgentId, firstAgentId === parent.id ? child.id : parent.id];+ for (const id of order) {+ if (retry && id === order[0]) {+ await expect(provisionFiles([Constants.EXECUTE_CODE], id)).rejects.toThrow(+ 'Failed to provision',+ );+ continue;+ }+ provisioned.set(id, await provisionFiles([Constants.EXECUTE_CODE], id));+ }+ if (retry) {+ provisioned.set(order[0], await provisionFiles([Constants.EXECUTE_CODE], order[0]));+ }+ expect(provisioned.get(parent.id)?.[0].name).toBe(parentPath);+ expect(provisioned.get(child.id)?.[0].name).toBe(childPath);+ expect(provisionToCodeEnv).toHaveBeenCalledTimes(retry ? 3 : 2);+ const merged = mergeCodeFilesIntoContext(+ {+ session_id: 'setup-store',+ files: [+ {+ id: 'setup-remote',+ name: liveName,+ storage_session_id: 'setup-store',+ kind: 'agent',+ resource_id: child.id,+ },+ ],+ },+ provisioned.get(child.id),+ );+ expect(merged?.files.map((entry) => entry.name)).toEqual([liveName, childPath]);+ },+ );++ it('locates queued files in the programmatic data directory for an attached workspace', () => {+ const agent: CodeFileAgent = {+ id: 'agent-a',+ provisionState: state([makeFile()], []),+ fileConsumers: { executeCode: true, fileSearch: false },+ codeExecutionContext: {+ baseUrl: 'https://code.example',+ codeSessionKey: 'attached',+ executionProfile: 'stateful',+ statefulSessions: true,+ environmentType: 'attached',+ codeWorkspace: {+ environmentId: 'personal-machine',+ workspaceId: 'project',+ operations: ['read_file'],+ },+ },+ };+ prepareQueuedCodeFileContext(agent, [agent], req.user?.id);++ expect(agent.dynamicToolContextMap?.queued_code_files).toContain(+ '$LIBRECHAT_CODE_DATA_DIR/data.csv',+ );+ expect(agent.dynamicToolContextMap?.queued_code_files).toContain('programmatic Bash');+ expect(agent.dynamicToolContextMap?.queued_code_files).not.toContain('/mnt/data/');+ });++ it('uploads colliding and converted files at the paths advertised before inference', async () => {+ const files = [+ makeFile({ file_id: 'first', filename: 'my dir/data.csv', text: 'preview' }),+ makeFile({ file_id: 'second', filename: 'data.csv' }),+ makeFile({ file_id: 'image', filename: 'photo.webp', type: 'image/png' }),+ ];+ const agent = {+ id: 'agent-a',+ provisionState: state(files, []),+ fileConsumers: { executeCode: true, fileSearch: false },+ dynamicToolContextMap: {},+ };+ prepareQueuedCodeFileContext(agent, [agent], req.user?.id);+ const advertised = new Map(agent.provisionState.codeEnvDestinations);+ const { provisionFiles, provisionToCodeEnv } = buildHarness({+ contexts: [[agent.id, agent]],+ });+ expect(provisionToCodeEnv).not.toHaveBeenCalled();+ expect(new Set(advertised.values()).size).toBe(3);+ expect(advertised.get('image')).toBe('photo.png');++ await provisionFiles([Constants.EXECUTE_CODE], agent.id);++ for (const [args] of provisionToCodeEnv.mock.calls) {+ expect(args.sandboxFilename).toBe(advertised.get(args.file.file_id));+ }+ expect(agent.provisionState.codeEnvFiles).toEqual([]);+ });+it('scopes only the agent own resource files to its identity', async () => {/* A user can attach another agent's setup file to this conversation. Uploading it under* this agent would place it in a namespace this agent's other users share, so thediff --git a/packages/api/src/files/provision/callback.ts b/packages/api/src/files/provision/callback.tsindex 462fe1beee..6e48fb0123 100644--- a/packages/api/src/files/provision/callback.ts+++ b/packages/api/src/files/provision/callback.ts@@ -1,23 +1,13 @@import { Constants } from '@librechat/agents';import { logger } from '@librechat/data-schemas';-import {- EToolResources,- getCodeEnvRefForProfile,- resolveSandboxFilename,-} from 'librechat-data-provider';-import type { AgentToolResources, TFile } from 'librechat-data-provider';+import { EToolResources } from 'librechat-data-provider';+import type { TFile } from 'librechat-data-provider';import type { CodeEnvFile } from '@librechat/agents';-import type { CodeEnvRefUpdate, CodeExecutionRoute, ProvisionService } from './service';-import type { ProvisionState } from '~/agents/resources';+import type { CodeEnvRefUpdate, ProvisionService } from './service';+import type { ProvisionToolContext } from '../code/queued';import type { ServerRequest } from '~/types';-import {- claimCodeDestination,- createCodeDestinationSet,- reserveCodeDestination,- sortCodeFilesByDestinationPriority,-} from '~/files/code/destinations';import { createCodeApiRateLimitBudget, isCodeApiRateLimitError } from '~/utils';-import { getCodeEnvUploadFilename } from '../code/form';+import { planCodeFileUploads } from '../code/queued';import { isCodeFileToolName } from '~/agents/tools';/** Deferred database write produced by a successful provisioning call. */@@ -46,15 +36,7 @@ async function persistWithRetry(return false;}-/** The slice of a per-agent tool context this callback reads and updates. */-export interface ProvisionToolContext {- provisionState?: ProvisionState;- tool_resources?: AgentToolResources;- /** Code API deployment this agent resolved, so uploads land where it will execute. */- codeExecutionContext?: CodeExecutionRoute;- /** Successful refs retained while another file in the same batch awaits retry. */- pendingProvisionedCodeFiles?: CodeEnvFile[];-}+export type { ProvisionToolContext } from '../code/queued';export interface ProvisionCallbackDeps {req: ServerRequest;@@ -259,93 +241,24 @@ export function createProvisionFilesCallback({? [...(ctx.pendingProvisionedCodeFiles ?? [])]: [];if (needsCode && provisionState.codeEnvFiles.length > 0) {- const queuedFileIds = new Set(provisionState.codeEnvFiles.map((file) => file.file_id));- const liveFiles =- (ctx.tool_resources as Record<string, { files?: TFile[] } | undefined>)[- EToolResources.execute_code- ]?.files ?? [];- const routePrivateFileIds = new Set<string>();- for (const candidate of agentToolContexts.values()) {- const route =- candidate.codeExecutionContext?.executionRouteKey ??- candidate.codeExecutionContext?.executionProfile ??- 'default';- if (route !== codeRouteKey) continue;- for (const id of candidate.provisionState?.agentScopedFileIds ?? [])- routePrivateFileIds.add(id);+ const uploads = planCodeFileUploads({+ context: ctx,+ contexts: agentToolContexts.values(),+ agentId: resolvedAgentId,+ userId: req.user?.id,+ useAdvertisedNames: true,+ });+ provisionState.codeEnvDestinations ??= new Map();+ for (const { file, destination } of uploads) {+ provisionState.codeEnvDestinations.set(file.file_id, destination);}- const confirmedDestinations = new Set<string>();- const queuedCodeFiles = sortCodeFilesByDestinationPriority(- [- ...provisionState.codeEnvFiles,- ...liveFiles.filter((file) => !queuedFileIds.has(file.file_id)),- ],- routePrivateFileIds,- )- .filter((file): file is TFile => {- if (!file) return false;- const ref = getCodeEnvRefForProfile(file.metadata, codeRouteKey);- const recovery = provisionState.codeEnvRecoveryNames?.get(file.file_id);- const entityId = entityIdForFile(file);- const isTargetScope =- ref != null &&- ref.kind === (entityId ? 'agent' : 'user') &&- ref.id === (entityId ?? req.user?.id);- let storedName = recovery?.isTargetScope ? recovery.name : undefined;- if (isTargetScope) storedName = ref?.sandboxFilename;- // Prefix conflicts are independent recoverable inputs; only equal stored paths- // identify superseded content. Foreign-scope refs are claimable hints too.- if (storedName == null) return true;- if (confirmedDestinations.has(storedName)) return false;- confirmedDestinations.add(storedName);- return true;- })- .filter((file) => queuedFileIds.has(file.file_id));- /** Every file in this tool-load batch shares one wait allowance. This- * prevents a large recovery set from multiplying the live-turn delay. */+ const queuedCodeFiles = uploads.map(({ file }) => file);+ /** Every file in this tool-load batch shares one wait allowance. */const codeApiRateLimitBudget = createCodeApiRateLimitBudget(req.config?.endpoints?.agents?.codeApiMaxRetryWaitMs,);- const destinations = createCodeDestinationSet();- // Live storage paths are immutable. Reserve the same route-wide set for every- // agent so private live resources cannot give a shared recovery divergent names.- for (const candidateContext of agentToolContexts.values()) {- const candidateRoute =- candidateContext.codeExecutionContext?.executionRouteKey ??- candidateContext.codeExecutionContext?.executionProfile ??- 'default';- if (candidateRoute !== codeRouteKey) continue;- const existingCodeFiles = (- candidateContext.tool_resources as- | Record<string, { files?: TFile[] } | undefined>- | undefined- )?.[EToolResources.execute_code]?.files;- for (const existing of existingCodeFiles ?? []) {- if (queuedFileIds.has(existing.file_id)) continue;- reserveCodeDestination(- destinations,- getCodeEnvRefForProfile(existing.metadata, codeRouteKey)?.sandboxFilename ??- resolveSandboxFilename(existing.filename, existing.type),- );- }- }- for (const existing of provisionedCodeFiles) {- claimCodeDestination(destinations, existing.name, existing.id);- }const results = await Promise.allSettled(- queuedCodeFiles.map(async (file) => {- const sandboxFilename = claimCodeDestination(- destinations,- getCodeEnvUploadFilename(- resolveSandboxFilename(- getCodeEnvRefForProfile(file.metadata, codeRouteKey)?.sandboxFilename ??- provisionState.codeEnvRecoveryNames?.get(file.file_id)?.name ??- file.filename,- file.type,- ),- ),- file.file_id,- );+ uploads.map(async ({ file, destination: sandboxFilename }) => {const provisioned = await shareProvisioning(shareKey(`code:${codeRouteKey}`, file, sandboxFilename),async () => {