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
🦘 feat: Share Run-Scoped Files With Subagents (#15848)
Joseph Licataf25242df98f1
diff --git a/api/package.json b/api/package.jsonindex 1288ab39a0..b7a01ed44c 100644--- a/api/package.json+++ b/api/package.json@@ -46,7 +46,7 @@"@azure/storage-blob": "^12.30.0","@google/genai": "^2.8.0","@keyv/redis": "5.1.6",- "@librechat/agents": "^3.8.5",+ "@librechat/agents": "^3.8.6","@librechat/api": "*","@librechat/data-schemas": "*","@microsoft/microsoft-graph-client": "^3.0.7",diff --git a/api/server/controllers/agents/__tests__/callbacks.spec.js b/api/server/controllers/agents/__tests__/callbacks.spec.jsindex 1d76042381..cd9c1cd2ae 100644--- a/api/server/controllers/agents/__tests__/callbacks.spec.js+++ b/api/server/controllers/agents/__tests__/callbacks.spec.js@@ -22,9 +22,8 @@ jest.mock('@librechat/api', () => ({}: null,),- isCodeSessionToolName: jest.fn((name) =>- ['execute_code', 'bash_tool', 'read_file'].includes(name),- ),+ isCodeArtifactToolOutput: jest.requireActual('@librechat/api').isCodeArtifactToolOutput,+ isCodeSessionToolName: jest.requireActual('@librechat/api').isCodeSessionToolName,}));jest.mock('@librechat/data-schemas', () => ({diff --git a/api/server/controllers/agents/callbacks.js b/api/server/controllers/agents/callbacks.jsindex 770688c601..6c295b6568 100644--- a/api/server/controllers/agents/callbacks.js+++ b/api/server/controllers/agents/callbacks.js@@ -26,6 +26,7 @@ const {createBackgroundCodeResultHandler: createCodeHarvestHandler,HOST_FILE_AUTHORING_ARTIFACT_KEY,isCodeSessionToolName,+ isCodeArtifactToolOutput,getModelRefusalInfo,shouldSignalSandboxStart,getToolInputValidationDetails,@@ -40,10 +41,6 @@ function isHostFileAuthoringArtifact(artifact) {return artifact?.[HOST_FILE_AUTHORING_ARTIFACT_KEY] === true;}-function isCodeArtifactToolOutput(output) {- return isCodeSessionToolName(output.name) || isHostFileAuthoringArtifact(output.artifact);-}-function getAttachmentOwnership(metadata) {const agentId = metadata?.executingAgentId ?? metadata?.agentId ?? metadata?.agent_id;const stepId = metadata?.stepId;diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.jsindex 58fc1824d7..d60dedacc3 100644--- a/api/server/controllers/agents/client.js+++ b/api/server/controllers/agents/client.js@@ -4912,6 +4912,7 @@ class AgentClient extends BaseClient {this.buildDetachedSubagentUsageRecorder(balanceConfig, transactionsConfig),),subagentTasks: this.options.subagentTasks,+ runFiles: this.options.runFiles,}).then((createdRun) => {if (!createdRun) {throw new Error('Failed to create run');@@ -5123,6 +5124,7 @@ class AgentClient extends BaseClient {} finally {/** An aborted/erroring run can still have completed compaction before* the failure; retain that model-visible state for actor reconciliation. */+ await this.options.runFiles?.close();this.eventActorSummary =getLatestEventActorSummary(this.contentParts) ?? this.eventActorSummary;/** A run that never came to exist has no state of its own: keep the@@ -5664,6 +5666,7 @@ class AgentClient extends BaseClient {this.buildDetachedSubagentUsageRecorder(balanceConfig, transactionsConfig),),subagentTasks: this.options.subagentTasks,+ runFiles: this.options.runFiles,});if (!run) {@@ -5787,6 +5790,7 @@ class AgentClient extends BaseClient {});}} finally {+ await this.options.runFiles?.close();this.eventActorSummary =getLatestEventActorSummary(this.contentParts) ?? this.eventActorSummary;/** A run that never came to exist has no state of its own: keep thediff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.jsindex f5653ec8b8..286b0b412f 100644--- a/api/server/services/Endpoints/agents/initialize.js+++ b/api/server/services/Endpoints/agents/initialize.js@@ -28,6 +28,15 @@ const {backgroundCompletionWakeupsEnabled,createLazyAgentHistoryResolver,resolveToolRoleGrants,+ createChatRunFileBindings,+ createAxiosInstance,+ getCodeApiAuthHeaders,+ getCodeExecutionBaseUrl,+ getAuthorizedRunFileSnapshot,+ encodeAndFormatDocuments,+ encodeAndFormatAudios,+ encodeAndFormatVideos,+ extractFileContext,} = require('@librechat/api');const {ResourceType,@@ -38,6 +47,7 @@ const {AgentCapabilities,normalizeServerName,Tools,+ VisionModes,MAX_SUBAGENT_GRAPH_NODES,MAX_SUBAGENT_RUN_CONFIGS,isEphemeralAgentId,@@ -86,6 +96,10 @@ const {const { logViolation } = require('~/cache');const db = require('~/models');const { getAppConfig } = require('~/server/services/Config');+const { getStrategyFunctions } = require('~/server/services/Files/strategies');+const { encodeAndFormat } = require('~/server/services/Files/images/encode');+const { processCodeOutput, runPreviewFinalize } = require('~/server/services/Files/Code/process');+const { determineFileType } = require('~/server/utils');const SUBAGENT_GRAPH_LOAD_CONCURRENCY = 4;@@ -346,6 +360,7 @@ const initializeClient = async ({* }>}*/const agentToolContexts = new Map();+ let runFileBindings;const resolveMcpServerName = (toolName, agentId) => {if (typeof toolName !== 'string' || typeof agentId !== 'string') {return undefined;@@ -400,7 +415,7 @@ const initializeClient = async ({if (trustedContext?.codeExecutionContext) {callbackMetadata.codeExecutionContext = trustedContext.codeExecutionContext;}- return artifactToolEndCallback(data, callbackMetadata);+ return runFileBindings.deliverToolEnd(artifactToolEndCallback, data, callbackMetadata);};/** @type {Map<string, import('@librechat/api').EndpointTokenConfig | undefined>} */const endpointTokenConfigByAgentId = new Map();@@ -413,8 +428,15 @@ const initializeClient = async ({runSignal: signal,foregroundRunId,ordinaryToolCancellation: ordinaryToolCancellationEnabled,- loadTools: async (toolNames, agentId, _configurable, callerCapabilityProjection, runSignal) => {- const ctx = agentToolContexts.get(agentId) ?? {};+ loadTools: async (+ toolNames,+ agentId,+ _configurable,+ callerCapabilityProjection,+ runSignal,+ executionContext,+ ) => {+ const ctx = runFileBindings.getContext(agentId, executionContext) ?? {};logger.debug(`[ON_TOOL_EXECUTE] ctx found: ${!!ctx.userMCPAuthMap}, agent: ${ctx.agent?.id}`);logger.debug(`[ON_TOOL_EXECUTE] toolRegistry size: ${ctx.toolRegistry?.size ?? 'undefined'}`);@@ -427,6 +449,10 @@ const initializeClient = async ({requestBody: runtimeRequestBody,toolNames,agent: ctx.agent,+ runFileCodeExecutionContext: runFileBindings.getCodeExecutionContext(+ agentId,+ executionContext,+ ),toolRegistry: ctx.toolRegistry,callerCapabilityProjection,backgroundToolNames: ctx.backgroundToolNames,@@ -1193,6 +1219,11 @@ const initializeClient = async ({agent,loadTools: createToolLoader(req, res, context.signal, streamId, true, jobCreatedAt),requestFiles,+ authorizedRunFiles: getAuthorizedRunFileSnapshot({+ policy: appConfig.endpoints?.agents?.fileSharing,+ agent: primaryConfig,+ files: primaryConfig.currentRequestAttachments,+ }),conversationId,parentMessageId,requestBody: runtimeRequestBody,@@ -1648,6 +1679,54 @@ const initializeClient = async ({}: null;+ runFileBindings = createChatRunFileBindings({+ req,+ contexts: agentToolContexts,+ createdAt: jobCreatedAt,+ requestFiles,+ audit: (event) => logger.info('[agents:run-files]', event),+ getInputs: () => primaryConfig.currentRequestAttachments,+ loadFiles: (fileIds) => db.getRunFileCandidates(fileIds, req.user.tenantId),+ filterFiles: filterFilesByAgentAccess,+ listPublications: db.listRunArtifacts,+ provisioning: {+ provisionToCodeEnv,+ provisionToVectorDB,+ updateFile: db.updateFile,+ updateCodeEnvRef: db.updateFileCodeEnvRef,+ addEmbeddedEntity: db.addFileEmbeddedEntity,+ },+ fileMethods: {+ claimRunArtifactFile: db.claimRunArtifactFile,+ publishRunArtifactFile: db.publishRunArtifactFile,+ findRunArtifactFile: db.findRunArtifactFile,+ },+ processCodeOutput,+ snapshotAdapter: {+ request: createAxiosInstance(),+ getAuthHeaders: getCodeApiAuthHeaders,+ getBaseURL: getCodeExecutionBaseUrl,+ determineFileType,+ },+ finalize: runPreviewFinalize,+ getStrategyFunctions,+ artifactPromises,+ emitAttachment: createAttachmentEmitter({ res, streamId, jobCreatedAt }),+ encoder: {+ getAgent: (agentId) => agentToolContexts.get(agentId)?.fileEncodingAgent,+ encodeImages: (request, files, params) =>+ encodeAndFormat(request, files, params, VisionModes.agents),+ encodeDocuments: encodeAndFormatDocuments,+ encodeAudios: encodeAndFormatAudios,+ encodeVideos: encodeAndFormatVideos,+ extractText: extractFileContext,+ },+ });+ toolExecuteOptions.runFiles = runFileBindings.session;+ toolExecuteOptions.provisionFiles = runFileBindings.wrapProvision(+ toolExecuteOptions.provisionFiles,+ );+const eventHandlers = getDefaultHandlers({res,contentParts,@@ -1697,6 +1776,7 @@ const initializeClient = async ({endpoint: isEphemeralAgentId(primaryConfig.id) ? primaryConfig.endpoint : EModelEndpoint.agents,subagentAggregatorsByToolCallId,subagentTasks,+ runFiles: runFileBindings.session,/** Resolved endpoint token/pricing config so spending and cost reflect* configured rates for custom-endpoint agents instead of defaults. */endpointTokenConfig: primaryConfig.endpointTokenConfig,diff --git a/api/server/services/Endpoints/agents/skillDeps.js b/api/server/services/Endpoints/agents/skillDeps.jsindex 2558ba021c..c8aa0f2b30 100644--- a/api/server/services/Endpoints/agents/skillDeps.js+++ b/api/server/services/Endpoints/agents/skillDeps.js@@ -289,6 +289,13 @@ function buildSkillPrimedIdsByName(manualSkillPrimes, alwaysApplySkillPrimes) {function buildAgentToolContext({ agent, config }) {return {agent,+ fileEncodingAgent: {+ provider: config.provider,+ endpoint: config.endpoint,+ model_parameters: config.model_parameters,+ imageDetail: config.imageDetail,+ agentContextAttachments: config.agentContextAttachments,+ },/** Per-agent resolved endpoint token/pricing config. Retained here because* `agentToolContexts` is the one map that holds every agent — including* pure subagents pruned from `agentConfigs` — so usage can be priced withdiff --git a/api/server/services/Files/Code/__tests__/process-traversal.spec.js b/api/server/services/Files/Code/__tests__/process-traversal.spec.jsindex ec28e907ab..99404f5404 100644--- a/api/server/services/Files/Code/__tests__/process-traversal.spec.js+++ b/api/server/services/Files/Code/__tests__/process-traversal.spec.js@@ -5,6 +5,7 @@ jest.mock('@librechat/data-schemas', () => ({}));jest.mock('@librechat/agents', () => ({+ ...jest.requireActual('@librechat/agents'),getCodeBaseURL: jest.fn(() => 'http://localhost:8000'),}));@@ -20,6 +21,7 @@ jest.mock('@librechat/api', () => {const http = require('http');const https = require('https');return {+ processCodeOutput: jest.requireActual('@librechat/api').processCodeOutput,resolveDownloadPath: (file) => file.storageKey || file.filepath,logAxiosError: jest.fn(),getBasePath: jest.fn(() => ''),@@ -47,7 +49,7 @@ jest.mock('@librechat/api', () => {withTimeout: async (promise) => promise,/* These traversal cases all use non-office filenames — keep the* inline (non-finalize) path so existing assertions on a single- * createFile call hold. */+ * commitCodeFile call hold. */hasOfficeHtmlPath: jest.fn(() => false),/* Identity-helper stub mirroring `packages/api/src/files/code/identity.ts`.* `processCodeOutput` calls this for every output download URL;@@ -78,6 +80,7 @@ jest.mock('~/models', () => ({getFiles: jest.fn().mockResolvedValue([]),updateFile: jest.fn(),claimCodeFile: jest.fn().mockResolvedValue({ file_id: 'mock-uuid', usage: 0 }),+ commitCodeFile: jest.fn().mockResolvedValue(true),}));const mockSaveBuffer = jest.fn().mockResolvedValue('/uploads/user123/mock-uuid__output.csv');@@ -105,7 +108,7 @@ jest.mock('~/server/services/Files/retention', () => ({}));const { getRetentionExpiry } = require('~/server/services/Files/retention');-const { createFile } = require('~/models');+const { commitCodeFile } = require('~/models');const { processCodeOutput } = require('../process');const baseParams = {@@ -151,7 +154,7 @@ describe('processCodeOutput path traversal protection', () => {mockSanitizeArtifactPath.mockReturnValueOnce('safe-output.csv');await processCodeOutput({ ...baseParams, name: 'unsafe/../../output.csv' });- const fileArg = createFile.mock.calls[0][0];+ const fileArg = commitCodeFile.mock.calls[0][0];expect(fileArg.filename).toBe('safe-output.csv');expect(fileArg.tenantId).toBe('tenantA');});@@ -173,7 +176,7 @@ describe('processCodeOutput path traversal protection', () => {await processCodeOutput({ ...baseParams, name: '../../../chart.png' });expect(mockSanitizeArtifactPath).toHaveBeenCalledWith('../../../chart.png');- const fileArg = createFile.mock.calls[0][0];+ const fileArg = commitCodeFile.mock.calls[0][0];expect(fileArg.filename).toBe('safe-chart.png');expect(fileArg.tenantId).toBe('tenantA');});diff --git a/api/server/services/Files/Code/process.js b/api/server/services/Files/Code/process.jsindex f42da0e77c..ed800aaf37 100644--- a/api/server/services/Files/Code/process.js+++ b/api/server/services/Files/Code/process.js@@ -1,5 +1,4 @@const path = require('path');-const { v4 } = require('uuid');const { logger } = require('@librechat/data-schemas');const { getCodeBaseURL } = require('@librechat/agents');const {@@ -24,6 +23,7 @@ const {extractCodeArtifactText,extractCodeArtifactRawText,extractCodeArtifactInspectionText,+ prepareCodeOutputBufferForInspection,getBoundedCodeOutputByteLimit,getExtractedTextFormat,getStorageMetadata,@@ -38,16 +38,14 @@ const {CODE_OUTPUT_PREFLIGHT_MAX_BYTES,CODE_OUTPUT_PREFLIGHT_MAX_COUNT,normalizeArtifactDeliveryFailure,+ processCodeOutput: processCodeOutputWithDeps,resolveDownloadPath,} = require('@librechat/api');const {Tools,megabyte,- fileConfig,FileContext,FileSources,- imageExtRegex,- inferMimeType,EToolResources,EModelEndpoint,ErrorTypes,@@ -56,7 +54,7 @@ const {getEndpointFileConfig,} = require('librechat-data-provider');const { filterFilesByAgentAccess } = require('~/server/services/Files/permissions');-const { createFile, getFiles, updateFile, claimCodeFile } = require('~/models');+const { getFiles, updateFile, claimCodeFile, commitCodeFile } = require('~/models');const { getStrategyFunctions } = require('~/server/services/Files/strategies');const { convertImage } = require('~/server/services/Files/images/convert');const { getRetentionExpiry } = require('~/server/services/Files/retention');@@ -315,66 +313,16 @@ const prepareCodeOutputForInspection = async ({executionProfile,executionRouteKey,});- const safeName = sanitizeArtifactPath(name);- const fallbackType = inferMimeType(name, '') || 'application/octet-stream';- if (!inspectContent) {- return {- buffer,- file: {- name,- filename: safeName,- type: fallbackType,- },- };- }- if (buffer.length > fileSizeLimit) {- return {- buffer,- extractedTextComplete: false,- file: {- name,- filename: safeName,- type: fallbackType,- },- };- }-- const detectedType = await determineFileType(buffer, true);- const detectedMimeType = detectedType?.mime?.toLowerCase();- if (detectedMimeType?.startsWith('image/')) {- return {- buffer,- extractedTextComplete: false,- file: {- name,- filename: safeName,- type: detectedMimeType,- },- };- }-- const leafName = path.basename(safeName);- const unknownText = detectedType == null ? extractCodeArtifactRawText(buffer, 'utf8-text') : null;- const mimeType = unknownText != null ? 'text/plain' : (detectedMimeType ?? fallbackType);- const category = unknownText != null ? 'utf8-text' : classifyCodeArtifact(leafName, mimeType);- const content = unknownText ?? extractCodeArtifactRawText(buffer, category);- const extractedText = await extractCodeArtifactInspectionText(+ return prepareCodeOutputBufferForInspection({buffer,- leafName,- mimeType,- category,- );- return {- buffer,- extractedTextComplete: extractedText.complete,- file: {- name,- filename: safeName,- type: mimeType,- content: content ?? undefined,- extractedText: extractedText.text ?? undefined,- },- };+ name,+ fileSizeLimit,+ inspectContent,+ determineFileType,+ classify: classifyCodeArtifact,+ extractRawText: extractCodeArtifactRawText,+ extractInspectionText: extractCodeArtifactInspectionText,+ });};/**@@ -636,490 +584,28 @@ const runPreviewFinalize = ({ finalize, fileId, previewRevision, onResolved }) =});};-/**- * Process code execution output files — downloads and saves both images- * and non-image files. All files are saved to local storage with- * `codeEnvRef` metadata for code env re-upload.- *- * Returns a two-part shape so callers can ship the attachment to the- * client immediately and run preview extraction in the background:- * - `file`: persisted metadata (file is on disk, downloadable, and- * has `status: 'pending'` if a preview is still being rendered).- * - `finalize` (optional): a thunk returning the deferred preview- * result promise. Present only when an inline HTML preview is- * expected (office buckets — DOCX/XLSX/XLS/ODS/CSV/PPTX). Caller- * decides whether to await or fire-and-forget.- *- * Existing fallback paths (size limit, missing storage strategy, error- * catch) return `{ file }` with no `finalize` — there's nothing to- * extract.- *- * @param {ServerRequest} params.req - The Express request object.- * @param {string} params.id - The file ID from the code environment.- * @param {string} params.name - The filename.- * @param {string} params.toolCallId - The tool call ID that generated the file.- * @param {string} params.session_id - The code execution session ID.- * @param {string} params.conversationId - The current conversation ID.- * @param {string} params.messageId - The current message ID.- * @param {string} [params.codeApiBaseUrl] - Trusted per-agent Code API endpoint.- * @param {'default'|'stateful'} [params.executionProfile] - Trusted execution profile.- * @param {string} [params.executionRouteKey] - Trusted deployment-local route identity.- * @param {string} [params.bridgeWorkerId] - Trusted bridge worker selected for this execution.- * @param {Buffer} [params.preparedBuffer] - Bytes downloaded during a- * no-write content inspection preflight.- * @param {boolean} [params.downloadFallback] - Return the bounded download- * fallback without downloading the generated bytes again.- * @returns {Promise<{ file: MongoFile & { messageId: string, toolCallId: string }, finalize?: () => Promise<MongoFile | null> }>}- */-const processCodeOutput = async ({- req,- id,- name,- toolCallId,- conversationId,- messageId,- session_id,- agentId,- freshClaimAfter,- codeApiBaseUrl,- executionProfile = 'default',- executionRouteKey = executionProfile,- bridgeWorkerId,- preparedBuffer,- downloadFallback,-}) => {- const appConfig = req.config;- const currentDate = new Date();- const fileExt = path.extname(name).toLowerCase();- const isImage = fileExt && imageExtRegex.test(name);-- const { endpointFileConfig, fileSizeLimit } = getCodeOutputFileSettings(req);-- try {- const formattedDate = currentDate.toISOString();- if (downloadFallback === true) {- return {- file: createDownloadFallback({- id,- name,- agentId,- messageId,- toolCallId,- session_id,- conversationId,- executionProfile,- executionRouteKey,- expiresAt: currentDate.getTime() + 86400000,- }),- };- }- const retentionExpiryPromise = getRetentionExpiry(req);- const buffer =- preparedBuffer ??- (await downloadCodeOutputBuffer({- req,- id,- session_id,- maxBytes: fileSizeLimit,- codeApiBaseUrl,- executionProfile,- bridgeWorkerId,- }));-- // Enforce file size limit- if (buffer.length > fileSizeLimit) {- logger.warn(- `[processCodeOutput] File "${name}" (${(buffer.length / megabyte).toFixed(2)} MB) exceeds size limit of ${(fileSizeLimit / megabyte).toFixed(2)} MB, falling back to download URL`,- );- return {- file: createDownloadFallback({- id,- name,- agentId,- messageId,- toolCallId,- session_id,- conversationId,- executionProfile,- executionRouteKey,- expiresAt: currentDate.getTime() + 86400000,- }),- };- }-- /* Code-output files belong to the user who ran the execution.- * SessionKey on codeapi will be `<tenant>:user:<userId>` for these,- * so cache and access stay user-private. */- const codeEnvRef = {- kind: 'user',- id: req.user.id,- storage_session_id: session_id,- file_id: id,- executionProfile,- ...(executionRouteKey !== executionProfile ? { executionRouteKey } : {}),- };-- /* `safeName` keeps the directory structure (`a/b/file.txt` -> `a/b/file.txt`)- * so the next prime() can place the file at the same nested path in the- * sandbox; flattening would re-create the bug where every nested artifact- * collapsed into the root and read_file calls 404'd. The flat-form- * storage key is composed below once `file_id` is known so we can cap- * the total length at filesystem NAME_MAX. */- const safeName = sanitizeArtifactPath(name);- if (safeName !== name) {- logger.warn(- `[processCodeOutput] Filename sanitized: "${name}" -> "${safeName}" | conv=${conversationId}`,- );- }-- /**- * Atomically claim a file_id for this (filename, conversationId, context) tuple.- * Uses $setOnInsert so concurrent calls for the same filename converge on- * a single record instead of creating duplicates (TOCTOU race fix).- *- * Claim by `safeName` (not raw `name`) so the claim and the eventual- * `createFile` agree on the filename column — otherwise weird inputs- * (e.g. `"proj name/[email protected]"`) would claim under the raw name and- * then write under the sanitized one, leaving the claim row orphaned.- */- /**- * Dispatch-order stamp persisted with every write AND every claim insert- * (foreground writes dispatch ≈ now): the out-of-order guard below- * compares WRITER dispatch order, not wall-clock write time — an older- * task writing late must not make a newer task's harvest look stale, and- * a freshly claimed row must carry its claimant's stamp before the- * content write lands.- */- const sourceDispatchedAt = freshClaimAfter ?? Date.now();-- const newFileId = v4();- const claimed = await claimCodeFile({- filename: safeName,- conversationId,- file_id: newFileId,- user: req.user.id,- tenantId: req.user.tenantId,- sourceDispatchedAt,- });- const file_id = claimed.file_id;- const isUpdate = file_id !== newFileId;-- /**- * Out-of-order guard for detached (background) harvests: when the claimed- * row's last writer was dispatched AFTER this task (`freshClaimAfter` =- * this task's dispatch time), a newer run owns this filename slot. The- * `(filename, conversationId)` unique index means the stale bytes have- * nowhere else to live, so skip this file rather than overwrite fresh- * content — the harvest's stdout patch still lands, only the superseded- * attachment is omitted. Falls back to `updatedAt` for rows written- * before the stamp existed (the claim itself is timestamp-neutral).- */- const lastWriterDispatchedAt =- claimed.metadata?.sourceDispatchedAt ??- (claimed.updatedAt != null ? new Date(claimed.updatedAt).getTime() : null);- if (isUpdate && freshClaimAfter != null && lastWriterDispatchedAt > freshClaimAfter) {- logger.warn(- `[processCodeOutput] Skipping stale background output "${safeName}" (${file_id}): a newer run owns this filename`,- );- return null;- }-- if (isUpdate) {- logger.debug(- `[processCodeOutput] Updating existing file "${safeName}" (${file_id}) instead of creating duplicate`,- );- }-- /**- * Background harvests commit through a CONDITIONAL write: the ownership- * predicate (last writer's dispatch stamp not newer than ours) is part of- * the update's filter, so check and write are one atomic operation — a- * stale harvest's commit simply misses and its attachment is skipped.- * The row always exists here (the claim inserted it), so the non-upsert- * `updateFile` matches `createFile(data, true)` semantics ($set + TTL- * unset). Bytes a loser may have already uploaded to the shared storage- * key are a narrow residual that per-file locking would be needed to- * close. Foreground writes keep the unconditional `createFile` path.- */- const commitCodeFile = async (fileData) => {- if (freshClaimAfter == null) {- await createFile(fileData, true);- return true;- }- const committed = await updateFile(fileData, {- $or: [- { 'metadata.sourceDispatchedAt': { $exists: false } },- { 'metadata.sourceDispatchedAt': { $lte: sourceDispatchedAt } },- ],- });- if (!committed) {- logger.warn(- `[processCodeOutput] Skipping stale background output "${safeName}" (${file_id}): a newer run owns this filename`,- );- return false;- }- return true;- };-- /**- * Preserve the original `messageId` on update. Each `processCodeOutput`- * call would otherwise overwrite it with the current run's run id, which- * decouples the file from the assistant message that originally created- * it. `getCodeGeneratedFiles` filters by `messageId IN <thread>`, so a- * stale id (e.g. from a later regeneration / failed re-read attempt)- * silently excludes the file from priming on subsequent turns.- */- const persistedMessageId = isUpdate ? (claimed.messageId ?? messageId) : messageId;- /* A generated-output write replaces the file's bytes, so pointers to- * earlier content in another profile must not survive as reusable refs. */- const codeEnvReferenceSet = mergeCodeEnvRef(undefined, codeEnvRef);- const codeEnvMetadata = {- ...claimed.metadata,- ...codeEnvReferenceSet,- sourceDispatchedAt,- };-- if (isImage) {- const usage = isUpdate ? (claimed.usage ?? 0) + 1 : 1;- const _file = await convertImage(req, buffer, 'high', `${file_id}${fileExt}`);- const filepath = usage > 1 ? `${_file.filepath}?v=${Date.now()}` : _file.filepath;- const storageMetadata = getStorageMetadata({- filepath: _file.filepath,- source: appConfig.fileStrategy,- storageKey: _file.storageKey,- storageRegion: _file.storageRegion,- });- const file = {- ..._file,- filepath,- ...storageMetadata,- file_id,- messageId: persistedMessageId,- usage,- filename: safeName,- conversationId,- executionProfile,- user: req.user.id,- tenantId: req.user.tenantId,- type: `image/${appConfig.imageOutputType}`,- createdAt: isUpdate ? claimed.createdAt : formattedDate,- updatedAt: formattedDate,- source: appConfig.fileStrategy,- context: FileContext.execute_code,- metadata: codeEnvMetadata,- ...(await retentionExpiryPromise),- };- if (!(await commitCodeFile(file))) {- return null;- }- return { file: Object.assign(file, { messageId, toolCallId, agentId }) };- }-- const { saveBuffer } = getStrategyFunctions(appConfig.fileStrategy);- if (!saveBuffer) {- logger.warn(- `[processCodeOutput] saveBuffer not available for strategy ${appConfig.fileStrategy}, falling back to download URL`,- );- return {- file: createDownloadFallback({- id,- name,- agentId,- messageId,- toolCallId,- session_id,- conversationId,- executionProfile,- executionRouteKey,- expiresAt: currentDate.getTime() + 86400000,- }),- };- }-- const detectedType = await determineFileType(buffer, true);- const mimeType = detectedType?.mime || inferMimeType(name, '') || 'application/octet-stream';-- /** Check MIME type support - for code-generated files, we're lenient but log unsupported types */- const isSupportedMimeType = fileConfig.checkType(- mimeType,- endpointFileConfig.supportedMimeTypes,- );- if (!isSupportedMimeType) {- logger.warn(- `[processCodeOutput] File "${name}" has unsupported MIME type "${mimeType}", proceeding with storage but may not be usable as tool resource`,- );- }-- /* Compose the storage key here, after `file_id` is known, so the- * `flattenArtifactPath` cap budget can be calculated against the- * actual prefix length. The full key has to fit in one filesystem- * path component (NAME_MAX = 255 on most filesystems); without this- * cap, deeply-nested artifact paths whose individual segments were- * within bounds can still produce a flat form that overflows once- * `${file_id}__` is prepended, causing `ENAMETOOLONG` inside- * saveBuffer and falling back to a download URL. The 255 figure is- * the conservative cross-platform NAME_MAX (Linux ext4, NTFS, APFS).- */- const NAME_MAX = 255;- const flatName = flattenArtifactPath(safeName, NAME_MAX - file_id.length - 2);- const fileName = `${file_id}__${flatName}`;- const filepath = await saveBuffer({- userId: req.user.id,- buffer,- fileName,- basePath: 'uploads',- tenantId: req.user.tenantId,- });- const storageMetadata = getStorageMetadata({- filepath,- source: appConfig.fileStrategy,- });-- /* `classifyCodeArtifact` and `extractCodeArtifactText` make- * extension/bare-name decisions on the input string. With the- * path-preserving sanitizer they can now receive a nested path like- * `reports.v1/Makefile`, which the classifier's `extensionOf` reads- * as `v1/Makefile` (the slice after the dot in the directory name)- * and the bare-name branch rejects because it sees a `.` anywhere in- * the string. Result: extensionless artifacts under dotted folders- * (Makefile, Dockerfile, etc.) get misclassified as `other` and- * skip text extraction. Pass the basename so classification matches- * what it would have gotten with the old flat-name flow. */- const leafName = path.basename(safeName);- const category = classifyCodeArtifact(leafName, mimeType);-- /* Office-bucket files (DOCX/XLSX/XLS/ODS/CSV/PPTX) route through- * `bufferToOfficeHtml` which is CPU-heavy. Persist the record now- * with `status: 'pending'` and `text: null` so the agent's response- * isn't blocked, then return a `finalize` thunk the caller can run- * in the background. Non-office files have cheap or no extraction- * — run it inline so the caller gets a fully-resolved record- * without juggling a finalize step. */- const expectsPreview = hasOfficeHtmlPath(leafName, mimeType);-- const baseFile = {- file_id,- filepath,- ...storageMetadata,- messageId: persistedMessageId,- object: 'file',- filename: safeName,- type: mimeType,- conversationId,- user: req.user.id,- tenantId: req.user.tenantId,- bytes: buffer.length,- updatedAt: formattedDate,- metadata: codeEnvMetadata,- source: appConfig.fileStrategy,- context: FileContext.execute_code,- usage: isUpdate ? (claimed.usage ?? 0) + 1 : 1,- createdAt: isUpdate ? claimed.createdAt : formattedDate,- ...(await retentionExpiryPromise),- };-- if (expectsPreview) {- /* Persist with `status: 'pending'` and explicit- * `text: null` / `textFormat: null` so an update that previously- * had cached text gets cleared. The deferred finalize transitions- * to 'ready' (with text/textFormat) or 'failed' (with- * previewError).- *- * `previewRevision` is a fresh UUID stamped on every emit. The- * deferred finalize's `updateFile` is conditional on this — if- * a newer turn (cross-turn filename reuse) has rotated the- * revision before this render finishes, the stale render is- * silently discarded rather than overwriting the newer record.- * (Codex P1 review on PR #12957.) */- const previewRevision = v4();- const file = {- ...baseFile,- text: null,- textFormat: null,- status: 'pending',- previewError: null,- previewRevision,- };- if (!(await commitCodeFile(file))) {- return null;- }- return {- file: Object.assign(file, { messageId, toolCallId, agentId }),- finalize: () =>- finalizePreview({ buffer, leafName, mimeType, category, file_id, previewRevision }),- previewRevision,- };- }-- /* Non-office path: extraction is cheap (utf8 decode, parseDocument- * for PDF/ODT, or null for binaries). Run inline and return a- * fully-resolved record — no `finalize` needed. */- const text = await extractCodeArtifactText(buffer, leafName, mimeType, category);- /* `textFormat` accompanies `text` so the client can gate- * office-HTML-bucket routing on a trusted signal — clients MUST- * NOT inject `text` into the iframe as HTML unless `textFormat ===- * 'html'`. RAG-uploaded `.docx` etc. arrive with plain text from- * mammoth.extractRawText and would otherwise be hijacked by the- * extension-based office routing into the HTML-injection path- * (Codex P1 review on PR #12934). null on extract failure — the- * client treats absence as 'text' for safety. */- const textFormat = getExtractedTextFormat(leafName, mimeType, text);- const file = {- ...baseFile,- // Always set explicitly so an update which produces a binary or- // oversized artifact clears any previously cached text — createFile- // uses findOneAndUpdate with $set semantics.- text: text ?? null,- textFormat: textFormat ?? null,- // Clear deferred-preview lifecycle fields in case the prior emit- // at this (filename, conversationId) was an office file —- // otherwise stale `pending`/`failed` would persist and the client- // would render the wrong state for the now non-office artifact.- status: null,- previewError: null,- previewRevision: null,- };-- if (!(await commitCodeFile(file))) {- return null;- }- return { file: Object.assign(file, { messageId, toolCallId, agentId }) };- } catch (error) {- if (error?.code === 'CODE_OUTPUT_DOWNLOAD_LIMIT') {- logger.warn(- `[processCodeOutput] Generated file exceeds size limit of ${(fileSizeLimit / megabyte).toFixed(2)} MB, falling back to download URL`,- );- }- if (error?.message === 'Path traversal detected in filename') {- logger.warn(- `[processCodeOutput] Path traversal blocked for file "${name}" | conv=${conversationId}`,- );- }- logAxiosError({- message: 'Error downloading/processing code environment file',- error,- });- logger.warn(- `[processCodeOutput] Falling back to Code API download URL for strategy ${appConfig.fileStrategy}`,- );-- // Fallback for download errors - return download URL so user can still manually download- return {- file: createDownloadFallback({- id,- name,- agentId,- messageId,- toolCallId,- session_id,- conversationId,- executionProfile,- executionRouteKey,- expiresAt: currentDate.getTime() + 86400000,- }),- };- }-};+const processCodeOutput = (params) =>+ processCodeOutputWithDeps(params, {+ getCodeOutputFileSettings,+ downloadCodeOutputBuffer,+ createDownloadFallback,+ getRetentionExpiry,+ convertImage,+ getStrategyFunctions,+ determineFileType,+ claimCodeFile,+ commitCodeFile,+ finalizePreview,+ hasOfficeHtmlPath,+ sanitizeArtifactPath,+ flattenArtifactPath,+ classifyCodeArtifact,+ extractCodeArtifactText,+ getExtractedTextFormat,+ getStorageMetadata,+ logAxiosError,+ logger,+ });function getSessionFileInfo(ref, req, route = {}, signal) {return getCodeFileInfo({diff --git a/api/server/services/Files/Code/process.spec.js b/api/server/services/Files/Code/process.spec.jsindex e1508e665f..0a87df47bc 100644--- a/api/server/services/Files/Code/process.spec.js+++ b/api/server/services/Files/Code/process.spec.js@@ -64,6 +64,9 @@ const mockParseSandboxImageChunk = jest.fn((response) => response);const passthroughWithTimeout = async (promise) => promise;jest.mock('@librechat/api', () => {return {+ processCodeOutput: jest.requireActual('@librechat/api').processCodeOutput,+ prepareCodeOutputBufferForInspection:+ jest.requireActual('@librechat/api').prepareCodeOutputBufferForInspection,resolveDownloadPath: (file) => file.storageKey || file.filepath,logAxiosError: jest.fn(),/* Behaviourally identical to the real predicate in@@ -204,12 +207,14 @@ jest.mock('@librechat/agents', () => ({// Mock modelsconst mockClaimCodeFile = jest.fn();+const mockCommitCodeFile = jest.fn();const mockUpdateFile = jest.fn();jest.mock('~/models', () => ({createFile: jest.fn().mockResolvedValue({}),getFiles: jest.fn(),updateFile: mockUpdateFile,claimCodeFile: (...args) => mockClaimCodeFile(...args),+ commitCodeFile: mockCommitCodeFile,}));// Mock permissions (must be before process.js import)@@ -298,6 +303,8 @@ describe('Code Process', () => {});getFiles.mockResolvedValue(null);createFile.mockResolvedValue({});+ mockCommitCodeFile.mockReset();+ mockCommitCodeFile.mockResolvedValue(true);getStrategyFunctions.mockReturnValue({saveBuffer: jest.fn().mockResolvedValue('/uploads/mock-file-path.txt'),});@@ -329,7 +336,7 @@ describe('Code Process', () => {},});expect(mockClaimCodeFile).not.toHaveBeenCalled();- expect(createFile).not.toHaveBeenCalled();+ expect(mockCommitCodeFile).not.toHaveBeenCalled();expect(getStrategyFunctions).not.toHaveBeenCalled();});@@ -340,7 +347,7 @@ describe('Code Process', () => {expect(mockAxios).not.toHaveBeenCalled();expect(mockClaimCodeFile).toHaveBeenCalledTimes(1);- expect(createFile).toHaveBeenCalledTimes(1);+ expect(mockCommitCodeFile).toHaveBeenCalledTimes(1);});it('enforces a caller-provided aggregate inspection budget while downloading', async () => {@@ -360,7 +367,7 @@ describe('Code Process', () => {}),);expect(mockClaimCodeFile).not.toHaveBeenCalled();- expect(createFile).not.toHaveBeenCalled();+ expect(mockCommitCodeFile).not.toHaveBeenCalled();});it('extracts text bytes even when the generated filename spoofs an image extension', async () => {@@ -400,7 +407,150 @@ describe('Code Process', () => {});expect(mockAxios).not.toHaveBeenCalled();expect(mockClaimCodeFile).not.toHaveBeenCalled();- expect(createFile).not.toHaveBeenCalled();+ expect(mockCommitCodeFile).not.toHaveBeenCalled();+ });+ });++ describe('published run artifacts', () => {+ const scope = {+ userId: 'user-123',+ conversationId: 'conv-123',+ runId: 'parent-run',+ executionId: 'child-run',+ agentId: 'child-agent',+ sourceFileId: 'file-id-123',+ };+ const provenance = {+ runId: scope.runId,+ executionId: scope.executionId,+ agentId: scope.agentId,+ sourceFileId: scope.sourceFileId,+ parentExecutionId: 'parent-execution',+ publishedAt: '2026-09-11T16:00:00.000Z',+ inputFileIds: ['input-pdf'],+ };++ it('stores the existing output pipeline result through the publication boundary', async () => {+ const publish = jest.fn(async ({ file }) => ({+ ...file,+ file_id: 'published-id',+ user: scope.userId,+ conversationId: scope.conversationId,+ context: FileContext.run_artifact,+ metadata: { ...file.metadata, runFile: provenance },+ }));+ const discard = jest.fn();+ const result = await processCodeOutput({+ ...baseParams,+ preparedBuffer: Buffer.from('report data'),+ publication: { scope, provenance, publish, find: jest.fn(), discard },+ });+ expect(result.file).toMatchObject({+ file_id: 'published-id',+ filename: baseParams.name,+ context: FileContext.run_artifact,+ metadata: { runFile: provenance },+ });+ expect(publish).toHaveBeenCalledWith(expect.objectContaining({ scope, provenance }));+ expect(mockClaimCodeFile).not.toHaveBeenCalled();+ expect(mockCommitCodeFile).not.toHaveBeenCalled();+ expect(discard).not.toHaveBeenCalled();+ });++ it('finalizes office previews against the canonical published file identity', async () => {+ mockHasOfficeHtmlPath.mockReturnValueOnce(true);+ const publish = jest.fn(async ({ file }) => ({+ ...file,+ file_id: 'published-office-id',+ user: scope.userId,+ conversationId: scope.conversationId,+ context: FileContext.run_artifact,+ metadata: { ...file.metadata, runFile: provenance },+ }));+ const result = await processCodeOutput({+ ...baseParams,+ name: 'report.csv',+ preparedBuffer: Buffer.from('a,b\n1,2'),+ publication: { scope, provenance, publish, find: jest.fn(), discard: jest.fn() },+ });+ expect(result.file.file_id).toBe('published-office-id');+ expect(result.file.status).toBe('pending');+ await result.finalize();+ expect(require('~/models').updateFile).toHaveBeenCalledWith(+ expect.objectContaining({ file_id: 'published-office-id' }),+ { previewRevision: result.previewRevision },+ );+ });++ it('cleans a stored publication attempt when classification fails before metadata commit', async () => {+ const { createRunArtifactPublisher } = jest.requireActual('@librechat/api');+ const discard = jest.fn(async () => undefined);+ const publishRunArtifactFile = jest.fn();+ mockClassifyCodeArtifact.mockImplementationOnce(() => {+ throw new Error('Classification failed after storage');+ });+ const publish = createRunArtifactPublisher({+ claimRunArtifactFile: async () => ({ file_id: 'published-id' }),+ publishRunArtifactFile,+ findRunArtifactFile: async () => null,+ processCodeOutput: (input) => processCodeOutput({ ...input, req: mockReq }),+ prepare: async () => Buffer.from('report data'),+ discard,+ finalize: jest.fn(),+ });+ await expect(+ publish({+ scope,+ provenance,+ artifact: { id: baseParams.id, name: baseParams.name, sessionId: baseParams.session_id },+ }),+ ).rejects.toThrow('durable storage');+ expect(publishRunArtifactFile).not.toHaveBeenCalled();+ expect(discard).toHaveBeenCalledWith(+ expect.objectContaining({+ file_id: 'mock-uuid-1234',+ filepath: '/uploads/mock-file-path.txt',+ metadata: undefined,+ }),+ );+ expect(discard).toHaveBeenCalledTimes(1);+ });++ it('cleans a generated image cancelled after conversion without publishing it', async () => {+ const { createRunArtifactPublisher } = jest.requireActual('@librechat/api');+ const controller = new AbortController();+ const discard = jest.fn(async () => undefined);+ const publishRunArtifactFile = jest.fn();+ convertImage.mockImplementationOnce(async () => {+ controller.abort(new Error('Publication generation expired'));+ return { filepath: '/uploads/generated.webp', bytes: 12, width: 2, height: 2 };+ });+ const publish = createRunArtifactPublisher({+ claimRunArtifactFile: async () => ({ file_id: 'published-id' }),+ publishRunArtifactFile,+ findRunArtifactFile: async () => null,+ processCodeOutput: (input) => processCodeOutput({ ...input, req: mockReq }),+ prepare: async () => Buffer.from('image data'),+ discard,+ finalize: jest.fn(),+ });+ await expect(+ publish({+ scope,+ provenance,+ artifact: { id: baseParams.id, name: 'generated.png', sessionId: baseParams.session_id },+ signal: controller.signal,+ }),+ ).rejects.toThrow('generation expired');+ expect(publishRunArtifactFile).not.toHaveBeenCalled();+ expect(discard).toHaveBeenCalledWith(+ expect.objectContaining({+ filepath: '/uploads/generated.webp',+ file_id: 'mock-uuid-1234',+ metadata: undefined,+ }),+ );+ expect(discard).toHaveBeenCalledTimes(1);});});@@ -465,6 +615,7 @@ describe('Code Process', () => {});expect(result).toBeNull();+ expect(mockCommitCodeFile).not.toHaveBeenCalled();});it('still reuses the claim when it predates the background run', async () => {@@ -473,7 +624,7 @@ describe('Code Process', () => {filename: 'test-file.txt',updatedAt: '2024-01-01T00:00:00.000Z',});- mockUpdateFile.mockResolvedValue({ file_id: 'existing-file-id' });+ mockCommitCodeFile.mockResolvedValue(true);mockAxios.mockResolvedValue({ data: Buffer.alloc(100) });const { file: result } = await processCodeOutput({@@ -482,6 +633,10 @@ describe('Code Process', () => {});expect(result.file_id).toBe('existing-file-id');+ expect(mockCommitCodeFile).toHaveBeenCalledWith(+ expect.objectContaining({ file_id: 'existing-file-id' }),+ new Date('2024-01-02T00:00:00.000Z').getTime(),+ );});it('skips when a newer task holds an unwritten claim (insert stamp, no updatedAt yet)', async () => {@@ -502,17 +657,15 @@ describe('Code Process', () => {});expect(result).toBeNull();+ expect(mockCommitCodeFile).not.toHaveBeenCalled();});- it('commits background writes conditionally: an inserter overtaken mid-flight misses', async () => {- /* This task INSERTED the claim, then a newer task stamped and wrote- * while this one was still downloading — the ownership predicate is in- * the write's own filter, so the commit atomically misses. */+ it('omits output when the commit boundary rejects an overtaken claim', async () => {mockClaimCodeFile.mockResolvedValue({file_id: 'mock-uuid-1234',user: 'user-123',});- mockUpdateFile.mockResolvedValueOnce(null);+ mockCommitCodeFile.mockResolvedValueOnce(false);mockAxios.mockResolvedValue({ data: Buffer.alloc(100) });const result = await processCodeOutput({@@ -521,18 +674,14 @@ describe('Code Process', () => {});expect(result).toBeNull();- expect(mockUpdateFile).toHaveBeenCalledWith(- expect.objectContaining({ file_id: 'mock-uuid-1234' }),- {- $or: [- { 'metadata.sourceDispatchedAt': { $exists: false } },- {- 'metadata.sourceDispatchedAt': {- $lte: new Date('2024-01-01T00:00:00.000Z').getTime(),- },- },- ],- },+ expect(mockCommitCodeFile).toHaveBeenCalledWith(+ expect.objectContaining({+ file_id: 'mock-uuid-1234',+ metadata: expect.objectContaining({+ sourceDispatchedAt: new Date('2024-01-01T00:00:00.000Z').getTime(),+ }),+ }),+ new Date('2024-01-01T00:00:00.000Z').getTime(),);});@@ -542,7 +691,7 @@ describe('Code Process', () => {filename: 'test-file.txt',updatedAt: '2024-01-01T00:00:00.000Z',});- mockUpdateFile.mockResolvedValueOnce({ file_id: 'existing-file-id' });+ mockCommitCodeFile.mockResolvedValueOnce(true);mockAxios.mockResolvedValue({ data: Buffer.alloc(100) });const { file: result } = await processCodeOutput({@@ -565,7 +714,7 @@ describe('Code Process', () => {sourceDispatchedAt: new Date('2024-01-01T00:00:00.000Z').getTime(),},});- mockUpdateFile.mockResolvedValue({ file_id: 'existing-file-id' });+ mockCommitCodeFile.mockResolvedValue(true);mockAxios.mockResolvedValue({ data: Buffer.alloc(100) });const { file: result } = await processCodeOutput({@@ -641,9 +790,9 @@ describe('Code Process', () => {expect(mockClaimCodeFile).toHaveBeenCalledWith(expect.objectContaining({ tenantId: 'tenantA' }),);- expect(createFile).toHaveBeenCalledWith(+ expect(mockCommitCodeFile).toHaveBeenCalledWith(expect.objectContaining({ tenantId: 'tenantA' }),- true,+ undefined,);});@@ -748,7 +897,7 @@ describe('Code Process', () => {storageRegion: 'us-east-2',status: 'pending',});- expect(createFile).toHaveBeenCalledWith(+ expect(mockCommitCodeFile).toHaveBeenCalledWith(expect.objectContaining({file_id: 'mock-uuid-1234',user: 'user-123',@@ -757,7 +906,7 @@ describe('Code Process', () => {storageKey,storageRegion: 'us-east-2',}),- true,+ undefined,);expect(typeof finalize).toBe('function');});@@ -783,9 +932,9 @@ describe('Code Process', () => {expect(mockSaveBuffer).toHaveBeenCalledWith(expect.objectContaining({ tenantId: 'tenantA' }),);- expect(createFile).toHaveBeenCalledWith(+ expect(mockCommitCodeFile).toHaveBeenCalledWith(expect.objectContaining({ tenantId: 'tenantA' }),- true,+ undefined,);});@@ -917,9 +1066,9 @@ describe('Code Process', () => {'utf8-text',);expect(result.text).toBe('hello world\n');- expect(createFile).toHaveBeenCalledWith(+ expect(mockCommitCodeFile).toHaveBeenCalledWith(expect.objectContaining({ text: 'hello world\n' }),- true,+ undefined,);});@@ -933,7 +1082,7 @@ describe('Code Process', () => {const { file: result } = await processCodeOutput({ ...baseParams, name: 'archive.zip' });expect(result.text).toBeNull();- const createCall = createFile.mock.calls[0][0];+ const createCall = mockCommitCodeFile.mock.calls[0][0];expect(createCall.text).toBeNull();});@@ -955,7 +1104,7 @@ describe('Code Process', () => {await processCodeOutput({ ...baseParams, name: 'output.bin' });// null (not omitted) so $set clears any prior `text` value.- const createCall = createFile.mock.calls[0][0];+ const createCall = mockCommitCodeFile.mock.calls[0][0];expect(createCall).toHaveProperty('text', null);});@@ -989,7 +1138,7 @@ describe('Code Process', () => {await processCodeOutput({ ...baseParams, name: 'output.txt' });- const createCall = createFile.mock.calls[0][0];+ const createCall = mockCommitCodeFile.mock.calls[0][0];expect(createCall).toHaveProperty('status', null);expect(createCall).toHaveProperty('previewError', null);expect(createCall).toHaveProperty('previewRevision', null);@@ -1010,7 +1159,7 @@ describe('Code Process', () => {}),);expect(mockClaimCodeFile).toHaveBeenCalledTimes(1);- expect(createFile).toHaveBeenCalledTimes(1);+ expect(mockCommitCodeFile).toHaveBeenCalledTimes(1);});it('should fallback to download URL when file exceeds size limit', async () => {@@ -1031,8 +1180,8 @@ describe('Code Process', () => {expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('exceeds size limit'));expect(result.filepath).toContain('/api/files/code/download/session-123/file-id-123');expect(result.expiresAt).toBeDefined();- // Should not call createFile for oversized files (fallback path)- expect(createFile).not.toHaveBeenCalled();+ // Oversized files use the download fallback without committing metadata.+ expect(mockCommitCodeFile).not.toHaveBeenCalled();// Reset to default for other testsfileSizeLimitConfig.value = 20 * 1024 * 1024;@@ -1049,7 +1198,7 @@ describe('Code Process', () => {expect.stringContaining('Generated file exceeds size limit'),);expect(mockClaimCodeFile).not.toHaveBeenCalled();- expect(createFile).not.toHaveBeenCalled();+ expect(mockCommitCodeFile).not.toHaveBeenCalled();fileSizeLimitConfig.value = 20 * 1024 * 1024;});@@ -1262,18 +1411,18 @@ describe('Code Process', () => {expect(result.messageId).toBe('msg-123');});- it('should call createFile with upsert enabled', async () => {+ it('commits foreground output without a background dispatch constraint', async () => {const smallBuffer = Buffer.alloc(100);mockAxios.mockResolvedValue({ data: smallBuffer });await processCodeOutput(baseParams);- expect(createFile).toHaveBeenCalledWith(+ expect(mockCommitCodeFile).toHaveBeenCalledWith(expect.objectContaining({file_id: 'mock-uuid-1234',context: FileContext.execute_code,}),- true, // upsert flag+ undefined,);});});@@ -1301,18 +1450,18 @@ describe('Code Process', () => {*//**- * `processCodeOutput` mutates the file object after `createFile` returns+ * `processCodeOutput` mutates the file object after `commitCodeFile` returns* (`Object.assign(file, { messageId, toolCallId })`) so the runtime* caller sees the live messageId on the response. Reading- * `createFile.mock.calls[0][0]` directly would therefore reflect the+ * `mockCommitCodeFile.mock.calls[0][0]` directly would therefore reflect the* post-mutation state because JS captures by reference. To assert* what was actually PERSISTED, snapshot the args at call time.*/- function snapshotCreateFileArgs() {+ function snapshotCommitCodeFileArgs() {const snapshots = [];- createFile.mockImplementation(async (file) => {+ mockCommitCodeFile.mockImplementation(async (file) => {snapshots.push({ ...file });- return {};+ return true;});return snapshots;}@@ -1325,7 +1474,7 @@ describe('Code Process', () => {createdAt: '2024-01-01T00:00:00.000Z',messageId: 'turn-1-original-msg',});- const persisted = snapshotCreateFileArgs();+ const persisted = snapshotCommitCodeFileArgs();const smallBuffer = Buffer.alloc(100);mockAxios.mockResolvedValue({ data: smallBuffer });@@ -1348,7 +1497,7 @@ describe('Code Process', () => {createdAt: '2024-01-01T00:00:00.000Z',// messageId intentionally absent});- const persisted = snapshotCreateFileArgs();+ const persisted = snapshotCommitCodeFileArgs();const smallBuffer = Buffer.alloc(100);mockAxios.mockResolvedValue({ data: smallBuffer });@@ -1367,7 +1516,7 @@ describe('Code Process', () => {file_id: 'mock-uuid-1234',user: 'user-123',});- const persisted = snapshotCreateFileArgs();+ const persisted = snapshotCommitCodeFileArgs();const smallBuffer = Buffer.alloc(100);mockAxios.mockResolvedValue({ data: smallBuffer });@@ -1391,7 +1540,7 @@ describe('Code Process', () => {createdAt: '2024-01-01T00:00:00.000Z',messageId: 'turn-1-original-msg',});- const persisted = snapshotCreateFileArgs();+ const persisted = snapshotCommitCodeFileArgs();const smallBuffer = Buffer.alloc(100);mockAxios.mockResolvedValue({ data: smallBuffer });@@ -1418,7 +1567,7 @@ describe('Code Process', () => {createdAt: '2024-01-01T00:00:00.000Z',messageId: 'turn-1-image-msg',});- const persisted = snapshotCreateFileArgs();+ const persisted = snapshotCommitCodeFileArgs();const imageBuffer = Buffer.alloc(500);mockAxios.mockResolvedValue({ data: imageBuffer });@@ -1599,9 +1748,9 @@ describe('Code Process', () => {// Extractor MUST NOT have been called yet — that's deferred preview work.expect(mockExtractCodeArtifactText).not.toHaveBeenCalled();// Persisted record with the pending status.- expect(createFile).toHaveBeenCalledWith(+ expect(mockCommitCodeFile).toHaveBeenCalledWith(expect.objectContaining({ status: 'pending', text: null, textFormat: null }),- true,+ undefined,);});diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.jsindex bc7693cf34..acec96311b 100644--- a/api/server/services/ToolService.js+++ b/api/server/services/ToolService.js@@ -52,6 +52,7 @@ const {createGitIdentityProgrammaticBashTool,resolveCodeExecutionContext,resolveCodeExecutionWorkspaceContext,+ resolveRunFileCodeExecutionContext,resolveCallerCapabilityProjectionSnapshot,CREATE_FILE_TOOL_NAME,EDIT_FILE_TOOL_NAME,@@ -2050,6 +2051,7 @@ async function loadToolsForExecution({conversationId,actionsEnabled,accessibleMcpServerNames,+ runFileCodeExecutionContext,}) {const appConfig = req.config;const allLoadedTools = [];@@ -2148,6 +2150,10 @@ async function loadToolsForExecution({environments: req.config?.endpoints?.agents?.statefulCodeSessions?.environments,getAppConfig,});+ Object.assign(+ codeExecutionContext,+ resolveRunFileCodeExecutionContext(codeExecutionContext, runFileCodeExecutionContext),+ );configurable.codeExecutionContext = codeExecutionContext;const isPTC =diff --git a/client/src/components/Chat/Input/Files/Table/Columns.tsx b/client/src/components/Chat/Input/Files/Table/Columns.tsxindex dcf043b764..01195dfc55 100644--- a/client/src/components/Chat/Input/Files/Table/Columns.tsx+++ b/client/src/components/Chat/Input/Files/Table/Columns.tsx@@ -24,6 +24,7 @@ const contextMap: Record<any, TranslationKeys> = {[FileContext.image_generation]: 'com_ui_image_gen',[FileContext.assistants_output]: 'com_ui_assistants_output',[FileContext.message_attachment]: 'com_ui_attachment',+ [FileContext.run_artifact]: 'com_ui_published_file',};export const columns: ColumnDef<TFile>[] = [diff --git a/client/src/components/SidePanel/Agents/Advanced/AgentSubagents.tsx b/client/src/components/SidePanel/Agents/Advanced/AgentSubagents.tsxindex 8cdaadede9..84b00b3974 100644--- a/client/src/components/SidePanel/Agents/Advanced/AgentSubagents.tsx+++ b/client/src/components/SidePanel/Agents/Advanced/AgentSubagents.tsx@@ -12,9 +12,15 @@ interface AgentSubagentsProps {field: ControllerRenderProps<AgentForm, 'subagents'>;currentAgentId: string;maxSubagents: number;+ fileSharingEnabled?: boolean;}-const AgentSubagents: React.FC<AgentSubagentsProps> = ({ field, currentAgentId, maxSubagents }) => {+const AgentSubagents: React.FC<AgentSubagentsProps> = ({+ field,+ currentAgentId,+ maxSubagents,+ fileSharingEnabled = false,+}) => {const localize = useLocalize();const fieldValue = field.value;@@ -52,6 +58,13 @@ const AgentSubagents: React.FC<AgentSubagentsProps> = ({ field, currentAgentId,[field, value],);+ const setShareFiles = useCallback(+ (next: boolean) => {+ field.onChange({ ...value, shareFiles: next });+ },+ [field, value],+ );+const setAgentIds = useCallback((ids: string[]) => {field.onChange({@@ -119,6 +132,20 @@ const AgentSubagents: React.FC<AgentSubagentsProps> = ({ field, currentAgentId,}/>+ {fileSharingEnabled && (+ <ToggleSetting+ id="subagents-share-files-toggle"+ label={localize('com_ui_agent_subagents_share_files')}+ checked={value.shareFiles === true}+ onCheckedChange={setShareFiles}+ info={+ <p className="text-sm text-text-secondary">+ {localize('com_ui_agent_subagents_share_files_info')}+ </p>+ }+ />+ )}+<div className="flex flex-col gap-0.5"><ListMetalabel={localize('com_ui_agent_subagents_agents')}diff --git a/client/src/components/SidePanel/Agents/Advanced/OrchestrationHub.tsx b/client/src/components/SidePanel/Agents/Advanced/OrchestrationHub.tsxindex 87432631fc..e566356d62 100644--- a/client/src/components/SidePanel/Agents/Advanced/OrchestrationHub.tsx+++ b/client/src/components/SidePanel/Agents/Advanced/OrchestrationHub.tsx@@ -49,6 +49,7 @@ export default function OrchestrationHub({ currentAgentId }: OrchestrationHubProfield={field}currentAgentId={currentAgentId}maxSubagents={maxSubagents}+ fileSharingEnabled={agentsConfig?.fileSharing?.enabled === true}/>)}/>diff --git a/client/src/components/SidePanel/Agents/Advanced/__tests__/AgentSubagents.spec.tsx b/client/src/components/SidePanel/Agents/Advanced/__tests__/AgentSubagents.spec.tsxindex be3e5a4279..f64f41f39a 100644--- a/client/src/components/SidePanel/Agents/Advanced/__tests__/AgentSubagents.spec.tsx+++ b/client/src/components/SidePanel/Agents/Advanced/__tests__/AgentSubagents.spec.tsx@@ -41,7 +41,23 @@ jest.mock('../OrchestrationPattern', () => ({}));jest.mock('../ui', () => ({- ToggleSetting: () => null,+ ToggleSetting: ({+ label,+ checked,+ onCheckedChange,+ }: {+ label: string;+ checked: boolean;+ onCheckedChange: (checked: boolean) => void;+ }) => (+ <button+ type="button"+ role="switch"+ aria-label={label}+ aria-checked={checked}+ onClick={() => onCheckedChange(!checked)}+ />+ ),}));describe('AgentSubagents', () => {@@ -51,10 +67,16 @@ describe('AgentSubagents', () => {mockSubmit.mockReset();});- function Harness() {+ function Harness({+ fileSharingEnabled = false,+ initialSubagents,+ }: {+ fileSharingEnabled?: boolean;+ initialSubagents?: AgentForm['subagents'];+ }) {const methods = useForm<AgentForm>({defaultValues: {- subagents: {+ subagents: initialSubagents ?? {enabled: true,allowSelf: false,agent_ids: [],@@ -69,7 +91,12 @@ describe('AgentSubagents', () => {name="subagents"control={methods.control}render={({ field }) => (- <AgentSubagents field={field} currentAgentId="parent" maxSubagents={10} />+ <AgentSubagents+ field={field}+ currentAgentId="parent"+ maxSubagents={10}+ fileSharingEnabled={fileSharingEnabled}+ />)}/></form>@@ -108,4 +135,45 @@ describe('AgentSubagents', () => {expect(screen.getByText('com_ui_agent_subagents_empty')).toHaveClass('text-text-warning');});++ it('keeps file sharing unavailable until the deployment enables it', () => {+ const initialSubagents = { enabled: true, shareFiles: true, agent_ids: ['child'] };+ render(<Harness initialSubagents={initialSubagents} />);++ expect(+ screen.queryByRole('switch', { name: 'com_ui_agent_subagents_share_files' }),+ ).not.toBeInTheDocument();+ expect(mockGetValues?.('subagents')).toEqual(initialSubagents);+ });++ it('saves the opt-in immediately while preserving the configured roster', async () => {+ render(+ <Harness+ fileSharingEnabled+ initialSubagents={{ enabled: true, allowSelf: false, agent_ids: ['child'] }}+ />,+ );+ const sharing = screen.getByRole('switch', { name: 'com_ui_agent_subagents_share_files' });+ expect(sharing).toHaveAttribute('aria-checked', 'false');++ fireEvent.click(sharing);+ fireEvent.submit(screen.getByRole('form', { name: 'agent form' }));++ await waitFor(() =>+ expect(mockSubmit).toHaveBeenCalledWith(+ expect.objectContaining({+ subagents: {+ enabled: true,+ allowSelf: false,+ shareFiles: true,+ agent_ids: ['child'],+ },+ }),+ expect.anything(),+ ),+ );++ fireEvent.click(sharing);+ expect(mockGetValues?.('subagents.shareFiles')).toBe(false);+ });});diff --git a/client/src/components/SidePanel/Files/__tests__/PanelTable.spec.tsx b/client/src/components/SidePanel/Files/__tests__/PanelTable.spec.tsxindex 2639d3c100..b7ebba77c6 100644--- a/client/src/components/SidePanel/Files/__tests__/PanelTable.spec.tsx+++ b/client/src/components/SidePanel/Files/__tests__/PanelTable.spec.tsx@@ -1,10 +1,10 @@import React from 'react';import { render, screen, fireEvent } from '@testing-library/react';-import { FileSources } from 'librechat-data-provider';+import { FileSources, FileContext } from 'librechat-data-provider';import type { TFile } from 'librechat-data-provider';import type { ExtendedFile } from '~/common';-import DataTable from '../PanelTable';import { columns } from '../PanelColumns';+import DataTable from '../PanelTable';const mockShowToast = jest.fn();const mockAddFile = jest.fn();@@ -155,6 +155,39 @@ describe('PanelTable handleFileClick', () => {expect(mockShowToast).not.toHaveBeenCalledWith(expect.objectContaining({ status: 'error' }));});+ it('reattaches a persisted published file with its durable identity and provenance', () => {+ const runFile = {+ runId: 'run-1',+ executionId: 'child-execution',+ parentExecutionId: 'parent-execution',+ agentId: 'child-agent',+ sourceFileId: 'private-file',+ publishedAt: '2026-09-11T16:00:00.000Z',+ inputFileIds: ['input-pdf'],+ };+ const file = makeFile({+ file_id: 'published-report',+ filename: 'report.pdf',+ context: FileContext.run_artifact,+ metadata: { runFile },+ });+ mockFileMap = { [file.file_id]: file };++ renderTable([file]);+ clickFilenameCell();++ expect(mockAddFile).toHaveBeenCalledWith(+ expect.objectContaining({+ file_id: 'published-report',+ filename: 'report.pdf',+ filepath: file.filepath,+ metadata: { runFile },+ attached: true,+ progress: 1,+ }),+ );+ });+it('blocks attachment when fileLimit is reached', () => {const file = makeFile({ file_id: 'new-file', filename: 'new.pdf' });mockFileMap = { [file.file_id]: file };diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex b80732b296..424d63110d 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -890,6 +890,8 @@"com_ui_agent_subagents_info_2": "Enabling with no agents listed still allows self-spawn, so this agent can delegate focused subtasks to a fresh copy of itself.","com_ui_agent_subagents_max": "Maximum {{0}} subagents reached.","com_ui_agent_subagents_remove": "Remove {{0}} from subagents",+ "com_ui_agent_subagents_share_files": "Share files with subagents",+ "com_ui_agent_subagents_share_files_info": "Share this message's files with authorized foreground subagents. Generated sandbox files stay private while subagents inspect and refine them. Subagents choose which versions to publish.","com_ui_agent_subagents_subtitle": "Spin up helper agents to handle subtasks.","com_ui_agent_url_copied": "Agent URL copied to clipboard","com_ui_agent_var": "{{0}} agent",@@ -1880,6 +1882,7 @@"com_ui_ptc_trace_interrupted": "interrupted","com_ui_ptc_trace_running": "running","com_ui_ptc_trace_title": "Tool calls",+ "com_ui_published_file": "Published file","com_ui_quality": "Quality","com_ui_question_failed": "Question wasn't shown","com_ui_question_failed_description": "The agent couldn't show this question and may retry automatically.",diff --git a/docs/run_files.md b/docs/run_files.mdnew file mode 100644index 0000000000..f45a625ae9--- /dev/null+++ b/docs/run_files.md@@ -0,0 +1,131 @@+# Run-scoped files for subagents++An agent with file sharing enabled can delegate the files attached to the current message.+Children receive an authorized file catalog and use the existing native-provider, extracted-text,+code, or search paths. Code and search copies are provisioned when their tools need them.+Earlier conversation attachments and another agent's setup files are not added to this catalog.+Files explicitly routed only to tools still obey upload policy, but do not consume the receiving+model's attachment budget. Files resolved to provider or extracted-text delivery do consume it.++Enable the deployment capability in `librechat.yaml`, then enable **Share files with subagents**+in the parent agent's subagent settings:++```yaml+endpoints:+ agents:+ fileSharing:+ enabled: true+ allowSiblingSharing: false+ maxFiles: 100+ maxPrivateBytes: 268435456+ ttlMs: 3600000+```++The deployment capability and each agent's `subagents.shareFiles` setting default to disabled.+Existing saved agents do not need a migration. The limit bounds the run's file catalog and+private output references. `maxPrivateBytes` bounds the aggregate private snapshots stored on disk+for a run; it defaults to 256 MiB and can be configured up to 10 GiB. Reaching either limit rejects+a new capture while leaving existing versions usable. The lifetime begins at the generation's+creation time.++## Reading and publishing++`list_run_files` returns the current execution's permitted file IDs, delivery paths, provenance,+and unpublished artifact IDs. A child cannot enumerate another child's private outputs.+These tools are available to agents configured to delegate with file sharing enabled and to+child executions participating in that shared-file run. Enabling the deployment capability alone+does not add them to other agents.++Generated sandbox outputs stay private while a child reads, inspects, and refines them. The child can+create `analysis.csv`, inspect it in another tool call, and rewrite that filename without losing+the earlier version. Retained versions have separate artifact IDs, even when their filenames+match. Reading an unchanged file reuses its latest private version; changing a file and then+restoring earlier bytes creates another version. Catalogs list versions in creation order.+Select an artifact ID from `list_run_files` to choose the version to publish.++`publish_artifact` accepts an `artifact_id` from that list and returns a durable `file_id`.+It persists through the ordinary upload/storage/preview pipeline before notifying the parent.+The attachment appears in the conversation and Files panel, where it can be downloaded or+attached to another message. Publication records preserve user, tenant, conversation, run,+execution, producing agent, and input-file provenance. Retrying a successful publication returns+the same file ID; deleting that file does not let a cached retry restore it.+Publishing an earlier and a later version creates separate durable files. Later sandbox changes+do not change the bytes of either publication.++Search citations, memory updates, interactive tool resources, and image-generation results retain+their existing delivery behavior. They are not sandbox files in the publication catalog.++```mermaid+sequenceDiagram+ participant User+ participant Parent+ participant Child+ participant Files as Unified file storage+ User->>Parent: Message with uploaded PDF+ Parent->>Child: Delegate task and authorized input catalog+ Child->>Files: Provision PDF on first search/code use+ Child->>Child: Generate private CSV version 1+ Child->>Child: Inspect and refine into version 2+ Child->>Files: publish_artifact(selected version's artifact_id)+ Files-->>Parent: Durable file ID and attachment+ Parent-->>User: Response with downloadable CSV+```++Publication grants access to the producing execution and its parent chain. To grant another+authorized agent access, the deployment must also enable `allowSiblingSharing`, and the child+must supply that agent's ID in `recipient_agent_ids`. This does not grant execution permission+to agents outside the parent's configured subagent roster.++## Execution and recovery++Each child execution has its own managed sandbox partition, including simultaneous copies of+the same saved agent. Its own setup files retain their existing authorization. Code execution+within one partition is serialized through artifact capture; independent children can run+concurrently.++Unrelated tool batches reuse the authorized catalog after its initial load. File-consuming tools,+explicit catalog reads, delegation, publication, and completion refresh persisted publications so+deleted files leave the catalog and queued tool resources. Concurrent preparations join a pending+refresh rather than restoring an older catalog over its result.++Private output versions are captured before another sandbox operation can change their bytes.+Reading or running more code does not retire those versions. Publication uses the selected+captured version, so inspection and refinement can continue without changing a file being published.+Only explicit publication adds an output to the parent's catalog and the user's conversation.+Successful publication deletes its selected private snapshot after the durable file is stored.+Completion, cancellation, expiry, and a pause for human approval delete all remaining private+snapshots. An interrupted, paused, or reconstructed child must regenerate unpublished outputs.+Persisted publications can be rediscovered while the original run grant is valid.++Expiry and cancellation end temporary access; they do not delete durable user files. Durable+files use the existing file retention and deletion behavior and can be explicitly attached to a+new message. Audit events record inheritance, publication, and expiry without file contents.++## SDK dependency and current support++The dependency manifests require `@librechat/agents` 3.8.6 or later, and the lockfile installs 3.8.6.+This release includes the host-owned execution context from+[agents #539](https://github.com/danny-avila/agents/pull/539), exposing+`SUBAGENT_CONTEXT_VERSION = 1` and the `RunConfig.subagentContext` prepare/complete adapter.+A normal locked install includes the required SDK; no local SDK build is needed. The runtime+capability check rejects enabled sharing if an incompatible SDK is loaded.++The first implementation supports foreground chat delegation with managed code environments and+subagent teams whose members use the same provider, endpoint, model, Responses API setting, and+image-detail setting. An unset image detail inherits the request value, so it differs from an+explicit `auto` setting. Shared prompts are checked against every member's permanent attachments+before the files are encoded once for the team. The root's endpoint file budget also includes+retained historical and setup resources, counting each file once and releasing removed publications.+Detached child threads and background code+execution are disabled for shared-file runs until their durable task records can carry the same+authorization scope. Attached workstation environments, native provider tool objects without host+execution definitions, and API entry points without the run-file adapter fail explicitly when+sharing is requested.++The browser scenarios are `e2e/specs/mock/run-files.spec.ts`, `run-files-delivery.spec.ts`, and+`run-files-lifecycle.spec.ts`. They cover native PDF and extracted-text delivery, lazy search/code+provisioning, versioned publication, nested delegation, recipient authorization, concurrent runs,+cancellation cleanup, checkpoint recovery, reload, download, and follow-up attachment reuse.+They exercise the real application and SDK with deterministic model, Code API, and RAG fixtures.+Manifest, session, host, encoder, SDK bridge, publication storage, and config tests also cover+authorization, retries, individual child restoration, and default compatibility.diff --git a/e2e/config/librechat.e2e.yaml b/e2e/config/librechat.e2e.yamlindex dea966836d..ac380839b7 100644--- a/e2e/config/librechat.e2e.yaml+++ b/e2e/config/librechat.e2e.yaml@@ -80,6 +80,12 @@ mcpServers:# to llmDeliveryPath 'none' (unified-upload.spec.ts).fileConfig:endpoints:+ 'Mock Run Files':+ defaultLLMDeliveryPath:+ overrides:+ 'application/pdf': 'provider'+ 'text/plain': 'text'+ 'text/csv': 'none''Mock Provider A':legacyFileUploadUX: true'Mock Provider B':@@ -95,6 +101,9 @@ endpoints:# Default capabilities plus run_in_background (off by default upstream) so the# background tool-call e2e can opt an MCP tool into detached dispatch.agents:+ fileSharing:+ enabled: true+ allowSiblingSharing: truecapabilities:- deferred_tools- execute_code@@ -130,6 +139,15 @@ endpoints:# in model-fixture record mode (E2E_MODEL_FIXTURES=record); a comment# otherwise, so the credential-free profile never gains a live endpoint.# __E2E_MODEL_RECORD_PROVIDER__+ - name: 'Mock Run Files'+ apiKey: 'e2e-mock-run-files'+ baseURL: 'http://127.0.0.1:8889/v1'+ models:+ default:+ - 'mock-run-files'+ fetch: false+ titleConvo: false+ modelDisplayLabel: 'Mock Run Files'- name: 'Mock Provider A'apiKey: 'e2e-mock-key-a'baseURL: 'http://127.0.0.1:8889/v1'diff --git a/e2e/setup/fake-code-server.js b/e2e/setup/fake-code-server.jsindex 354f66c5d7..d441ac6fe1 100644--- a/e2e/setup/fake-code-server.js+++ b/e2e/setup/fake-code-server.js@@ -32,6 +32,8 @@ const sessions = new Map();const uploads = [];/** @type {Array<{ lang: string; codeLength: number; fileCount: number }>} */const execs = [];+/** @type {Map<string, { name: string; content: Buffer }>} */+const generated = new Map();function sessionIdFor(kind, id) {return `sess-${kind || 'user'}-${id || 'anon'}`;@@ -155,6 +157,42 @@ async function handleUploadBatch(req, res) {});}+function handleRunFileVersion(body, res, label, operation) {+ const sessionId = `e2e-run-file-versions-${label}`;+ const fileId = `e2e-versioned-${label}`;+ const name = 'analysis.csv';+ const key = `${sessionId}/${fileId}`;+ const files = Array.isArray(body.files) ? body.files : [];+ const inputNames = [`e2e-run-file-versions-${label}.pdf`, `e2e-run-file-versions-${label}.csv`];+ if (!inputNames.every((filename) => files.some((file) => file.name === filename))) {+ sendJson(res, 400, { message: 'version scenario requires both current uploaded inputs' });+ return;+ }+ if (+ operation !== 'write-v1' &&+ (!generated.has(key) ||+ !files.some((file) => file.id === fileId && file.storage_session_id === sessionId))+ ) {+ sendJson(res, 400, { message: 'version scenario lost the previous sandbox output' });+ return;+ }+ if (operation !== 'inspect') {+ const content = Buffer.from(+ operation === 'write-v1' ? 'version,total\n1,30\n' : 'version,total\n2,35\n',+ );+ /** Reuse the storage identity so only LibreChat's capture can preserve earlier bytes. */+ generated.set(key, { name, content });+ sessions.set(sessionId, [{ fileId, filename: name }]);+ }+ const file = generated.get(key);+ sendJson(res, 200, {+ session_id: sessionId,+ stdout: `${operation} ${name}\n${file.content.toString('utf8')}`,+ stderr: '',+ files: [{ id: fileId, name }],+ });+}+async function handleExec(req, res) {const body = await readJson(req);execs.push({@@ -162,6 +200,29 @@ async function handleExec(req, res) {codeLength: typeof body.code === 'string' ? body.code.length : 0,fileCount: Array.isArray(body.files) ? body.files.length : 0,});+ const versionMarker = body.code?.match(+ /E2E_RUN_FILE_VERSION:([A-Za-z0-9-]+):(write-v1|inspect|write-v2)/,+ );+ if (versionMarker) {+ handleRunFileVersion(body, res, versionMarker[1], versionMarker[2]);+ return;+ }+ const runFileLabel = body.code?.match(/E2E_RUN_FILE_ARTIFACT:([A-Za-z0-9-]+)/)?.[1];+ if (runFileLabel) {+ const sessionId = `e2e-run-files-${runFileLabel}`;+ const fileId = `e2e-generated-${runFileLabel}`;+ const name = `e2e-run-files-${runFileLabel}.csv`;+ const content = Buffer.from('source,count\npdf,1\n');+ generated.set(`${sessionId}/${fileId}`, { name, content });+ sessions.set(sessionId, [{ fileId, filename: name }]);+ sendJson(res, 200, {+ session_id: sessionId,+ stdout: `Created ${name}\n`,+ stderr: '',+ files: [{ id: fileId, name }],+ });+ return;+ }sendJson(res, 200, { stdout: 'E2E code exec ok\n', stderr: '', files: [] });}@@ -183,6 +244,7 @@ const server = http.createServer((req, res) => {if (pathname === '/__debug/reset' && req.method === 'POST') {sessions.clear();+ generated.clear();uploads.length = 0;execs.length = 0;sendJson(res, 200, { ok: true });@@ -204,6 +266,24 @@ const server = http.createServer((req, res) => {return;}+ const downloadMatch = pathname.match(/^\/v1\/download\/([^/]+)\/([^/]+)$/);+ if (downloadMatch && req.method === 'GET') {+ const key = `${decodeURIComponent(downloadMatch[1])}/${decodeURIComponent(downloadMatch[2])}`;+ const file = generated.get(key);+ if (!file) {+ sendJson(res, 404, { message: 'file not found' });+ return;+ }+ res.writeHead(200, {+ 'Content-Type': 'text/csv',+ 'Content-Length': file.content.length,+ 'Content-Disposition': `attachment; filename="${file.name}"`,+ 'X-Original-Filename': file.name,+ });+ res.end(file.content);+ return;+ }+const filesMatch = pathname.match(/^\/v1\/files\/([^/]+)$/);if (filesMatch && req.method === 'GET') {sendJson(res, 200, sessions.get(decodeURIComponent(filesMatch[1])) ?? []);diff --git a/e2e/setup/fake-model.js b/e2e/setup/fake-model.jsindex 859836d2df..9f7b53440e 100644--- a/e2e/setup/fake-model.js+++ b/e2e/setup/fake-model.js@@ -13,6 +13,14 @@ const { FakeChatModel } = require('@librechat/agents');const { ChatGenerationChunk } = require('@langchain/core/outputs');const { AIMessageChunk } = require('@langchain/core/messages');const { tryBindReplay } = require('./model-replay');+const { runFileDeliveryResponses } = require('./run-files-model');+const { createRunFileLifecycleResponses } = require('./run-files-lifecycle-model');++const runFileLifecycle = createRunFileLifecycleResponses({+ findLastToolMessage,+ getContentText,+ messageType,+});const MOCK_REPLY = process.env.MOCK_LLM_REPLY || 'E2E mock reply: pong';const CHUNK_DELAY_MS = Number(process.env.MOCK_LLM_CHUNK_DELAY_MS) || 10;@@ -59,6 +67,11 @@ const SUBAGENT_RESULT_MARKER = 'E2E_SUBAGENT_RESULT:';const SUBAGENT_CHILD_MARKER = 'E2E_SUBAGENT_CHILD:';const SUBAGENT_ACTIVITY_MARKER = 'E2E_SUBAGENT_ACTIVITY:';const SUBAGENT_ACTIVITY_CHILD_MARKER = 'E2E_SUBAGENT_ACTIVITY_CHILD:';+const RUN_FILES_MARKER = 'E2E_RUN_FILES:';+const RUN_FILES_CHILD_MARKER = 'E2E_RUN_FILES_CHILD:';+const RUN_FILES_FOLLOWUP_MARKER = 'E2E_RUN_FILES_FOLLOWUP:';+const RUN_FILE_VERSIONS_MARKER = 'E2E_RUN_FILE_VERSIONS:';+const RUN_FILE_VERSIONS_CHILD_MARKER = 'E2E_RUN_FILE_VERSIONS_CHILD:';const SUBAGENT_MODEL_OVERRIDE_ERROR ='[e2e] Streamed subagent result coverage requires an @librechat/agents release with ' +'StandardGraph.setSubagentModelOverride';@@ -1410,6 +1423,288 @@ function subagentResultResponses(text) {};}+function findRunFile(value, filename) {+ if (!value || typeof value !== 'object') {+ return null;+ }+ if ((value.filename ?? value.name) === filename) {+ const id = value.artifact_id ?? value.file_id ?? value.id;+ if (typeof id === 'string' && id.length > 0) {+ return { ...value, id };+ }+ }+ for (const child of Object.values(value)) {+ const match = findRunFile(child, filename);+ if (match) {+ return match;+ }+ }+ return null;+}++function parseRunFileResult(message) {+ try {+ return JSON.parse(getContentText(message?.content));+ } catch {+ return null;+ }+}++function runFilesResponses(text) {+ const followup = getMarkerValue(text, RUN_FILES_FOLLOWUP_MARKER);+ if (followup) {+ const [label, fileId] = followup.split(':');+ const callId = `call_e2e_run_files_followup_${label}`;+ return {+ responses: [''],+ resolveInvocation: (messages) => {+ const result = findLastToolMessage(messages, callId);+ if (!result) {+ return {+ response: '',+ toolCalls: [{ id: callId, name: 'list_run_files', args: {}, type: 'tool_call' }],+ };+ }+ const file = findRunFile(parseRunFileResult(result), `e2e-run-files-${label}.csv`);+ return {+ response:+ file?.id === fileId+ ? `E2E run file followup ${fileId}`+ : `E2E run files failed: followup missing ${fileId}: ${getContentText(result.content)}`,+ };+ },+ };+ }++ const marker = getMarkerValue(text, RUN_FILES_MARKER);+ if (!marker) {+ return null;+ }+ const [childId, label] = marker.split(':');+ if (!childId || !/^[A-Za-z0-9-]+$/.test(label ?? '')) {+ return { responses: ['E2E run files failed: malformed scenario marker'] };+ }+ const childPrompt = `${RUN_FILES_CHILD_MARKER}${label}`;+ const inputName = `e2e-run-files-${label}.pdf`;+ const outputName = `e2e-run-files-${label}.csv`;+ const call = (phase, name, args = {}) => ({+ response: '',+ toolCalls: [{ id: `call_e2e_run_files_${label}_${phase}`, name, args, type: 'tool_call' }],+ });+ const resultFor = (messages, phase) =>+ findLastToolMessage(messages, `call_e2e_run_files_${label}_${phase}`);+ const failure = (reason, message) => ({+ response: `E2E run files failed: ${reason}: ${getContentText(message?.content)}`,+ });++ return {+ responses: [''],+ overrideSubagentModel: true,+ resolveInvocation: (messages) => {+ const isChild = messages.some(+ (message) =>+ ['human', 'user'].includes(messageType(message)) &&+ getContentText(message.content).includes(childPrompt),+ );+ if (isChild) {+ const inputs = resultFor(messages, 'inputs');+ if (!inputs) return call('inputs', 'list_run_files');+ if (!findRunFile(parseRunFileResult(inputs), inputName)) {+ return failure('child cannot see current PDF', inputs);+ }+ const search = resultFor(messages, 'search');+ if (!search) return call('search', 'file_search', { query: `e2e ${label}` });+ const code = resultFor(messages, 'code');+ if (!code) {+ return call('code', 'bash_tool', {+ command: `printf 'source,count\\npdf,1\\n' > /mnt/data/${outputName}\n# E2E_RUN_FILE_ARTIFACT:${label}`,+ });+ }+ const catalog = resultFor(messages, 'artifacts');+ if (!catalog) return call('artifacts', 'list_run_files');+ const artifact = findRunFile(parseRunFileResult(catalog), outputName);+ if (!artifact) return failure('child output was not staged', catalog);+ const publication = resultFor(messages, 'publish');+ if (!publication) return call('publish', 'publish_artifact', { artifact_id: artifact.id });+ const published = findRunFile(parseRunFileResult(publication), outputName);+ if (!published) return failure('publication returned no durable file', publication);+ return { response: `E2E run file published ${published.id}` };+ }++ const child = resultFor(messages, 'delegate');+ if (!child) {+ return call('delegate', 'subagent', {+ description: childPrompt,+ subagent_type: childId,+ });+ }+ const fileId = getContentText(child.content).match(/E2E run file published ([\w.:-]+)/)?.[1];+ if (!fileId) return failure('child returned no published reference', child);+ const catalog = resultFor(messages, 'parent');+ if (!catalog) return call('parent', 'list_run_files');+ const file = findRunFile(parseRunFileResult(catalog), outputName);+ if (file?.id !== fileId) return failure('parent cannot see the published reference', catalog);+ return { response: `E2E run files complete ${label} file=${fileId}` };+ },+ };+}++function runFileVersionsResponses(text) {+ const marker = getMarkerValue(text, RUN_FILE_VERSIONS_MARKER);+ if (!marker) return null;+ const [childId, label] = marker.split(':');+ if (!childId || !/^[A-Za-z0-9-]+$/.test(label ?? '')) {+ return { responses: ['E2E run file versions failed: malformed scenario marker'] };+ }+ const childPrompt = `${RUN_FILE_VERSIONS_CHILD_MARKER}${label}`;+ const outputName = 'analysis.csv';+ const call = (phase, name, args = {}) => ({+ response: '',+ toolCalls: [+ { id: `call_e2e_run_file_versions_${label}_${phase}`, name, args, type: 'tool_call' },+ ],+ });+ const resultFor = (messages, phase) =>+ findLastToolMessage(messages, `call_e2e_run_file_versions_${label}_${phase}`);+ const artifactsFor = (message) =>+ (parseRunFileResult(message)?.artifacts ?? []).filter(+ (artifact) => artifact.filename === outputName && typeof artifact.artifact_id === 'string',+ );+ const failure = (reason, message) => ({+ response: `E2E run file versions failed: ${reason}: ${getContentText(message?.content)}`,+ });++ return {+ responses: [''],+ overrideSubagentModel: true,+ resolveInvocation: (messages) => {+ const isChild = messages.some(+ (message) =>+ ['human', 'user'].includes(messageType(message)) &&+ getContentText(message.content).includes(childPrompt),+ );+ if (isChild) {+ const inputs = resultFor(messages, 'inputs');+ if (!inputs) return call('inputs', 'list_run_files');+ const inputCatalog = parseRunFileResult(inputs);+ if (+ !findRunFile(inputCatalog?.files, `e2e-run-file-versions-${label}.pdf`) ||+ !findRunFile(inputCatalog?.files, `e2e-run-file-versions-${label}.csv`)+ ) {+ return failure('child cannot see both current inputs', inputs);+ }+ const search = resultFor(messages, 'search');+ if (!search) return call('search', 'file_search', { query: `e2e ${label}` });+ const firstWrite = resultFor(messages, 'write_v1');+ if (!firstWrite) {+ return call('write_v1', 'bash_tool', {+ command: `printf 'version,total\\n1,30\\n' > /mnt/data/${outputName}\n# E2E_RUN_FILE_VERSION:${label}:write-v1`,+ });+ }+ const firstCatalog = resultFor(messages, 'after_v1');+ if (!firstCatalog) return call('after_v1', 'list_run_files');+ const initialIds = new Set(artifactsFor(inputs).map((artifact) => artifact.artifact_id));+ const firstArtifact = artifactsFor(firstCatalog).find(+ (artifact) => !initialIds.has(artifact.artifact_id),+ );+ if (!firstArtifact) return failure('first write has no private artifact', firstCatalog);+ const inspection = resultFor(messages, 'inspect');+ if (!inspection) {+ return call('inspect', 'bash_tool', {+ command: `cat /mnt/data/${outputName}\n# E2E_RUN_FILE_VERSION:${label}:inspect`,+ });+ }+ if (!getContentText(inspection.content).includes('version,total\n1,30')) {+ return failure('later Bash call cannot read version one', inspection);+ }+ const inspectionCatalog = resultFor(messages, 'after_inspect');+ if (!inspectionCatalog) return call('after_inspect', 'list_run_files');+ const inspectedIds = new Set(+ artifactsFor(inspectionCatalog).map((artifact) => artifact.artifact_id),+ );+ if (!inspectedIds.has(firstArtifact.artifact_id)) {+ return failure('inspection retired the original artifact ID', inspectionCatalog);+ }+ const secondWrite = resultFor(messages, 'write_v2');+ if (!secondWrite) {+ return call('write_v2', 'bash_tool', {+ command: `printf 'version,total\\n2,35\\n' > /mnt/data/${outputName}\n# E2E_RUN_FILE_VERSION:${label}:write-v2`,+ });+ }+ const secondCatalog = resultFor(messages, 'after_v2');+ if (!secondCatalog) return call('after_v2', 'list_run_files');+ const secondArtifacts = artifactsFor(secondCatalog);+ if (+ !secondArtifacts.some((artifact) => artifact.artifact_id === firstArtifact.artifact_id)+ ) {+ return failure('overwrite retired the original artifact ID', secondCatalog);+ }+ const secondArtifact = secondArtifacts.find(+ (artifact) => !inspectedIds.has(artifact.artifact_id),+ );+ if (!secondArtifact) return failure('changed write has no new artifact ID', secondCatalog);+ const firstPublication = resultFor(messages, 'publish_v1');+ if (!firstPublication) {+ return call('publish_v1', 'publish_artifact', { artifact_id: firstArtifact.artifact_id });+ }+ const firstPublished = findRunFile(parseRunFileResult(firstPublication), outputName);+ if (!firstPublished) return failure('version one publication failed', firstPublication);+ const remainingCatalog = resultFor(messages, 'after_publish_v1');+ if (!remainingCatalog) return call('after_publish_v1', 'list_run_files');+ if (+ !artifactsFor(remainingCatalog).some(+ (artifact) => artifact.artifact_id === secondArtifact.artifact_id,+ )+ ) {+ return failure('publishing version one retired version two', remainingCatalog);+ }+ const secondPublication = resultFor(messages, 'publish_v2');+ if (!secondPublication) {+ return call('publish_v2', 'publish_artifact', {+ artifact_id: secondArtifact.artifact_id,+ });+ }+ const secondPublished = findRunFile(parseRunFileResult(secondPublication), outputName);+ if (!secondPublished || secondPublished.id === firstPublished.id) {+ return failure('version two has no distinct durable file', secondPublication);+ }+ return {+ response:+ `E2E run file versions published v1=${firstPublished.id} v2=${secondPublished.id} ` ++ `artifact_v1=${firstArtifact.artifact_id} artifact_v2=${secondArtifact.artifact_id}`,+ };+ }++ const child = resultFor(messages, 'delegate');+ if (!child) {+ return call('delegate', 'subagent', {+ description: childPrompt,+ subagent_type: childId,+ });+ }+ const proof = getContentText(child.content).match(+ /E2E run file versions published v1=([\w.:-]+) v2=([\w.:-]+) artifact_v1=([\w.:-]+) artifact_v2=([\w.:-]+)/,+ );+ if (!proof) return failure('child returned no version publications', child);+ const catalog = resultFor(messages, 'parent');+ if (!catalog) return call('parent', 'list_run_files');+ const parentFiles = parseRunFileResult(catalog)?.files ?? [];+ if (+ ![proof[1], proof[2]].every((fileId) =>+ parentFiles.some((file) => file.file_id === fileId && file.filename === outputName),+ )+ ) {+ return failure('parent cannot see both published versions', catalog);+ }+ return {+ response:+ `E2E run file versions complete ${label} v1=${proof[1]} v2=${proof[2]} ` ++ `artifact_v1=${proof[3]} artifact_v2=${proof[4]}`,+ };+ },+ };+}+function parseSubagentActivityMarker(text) {const value = getMarkerValue(text, SUBAGENT_ACTIVITY_MARKER);const separator = value.indexOf(':');@@ -2414,11 +2709,27 @@ function codeExecResponses({ filename, toolCallId, finalText, code }, toolNames)}function resolveResponses({ graph, messages, text, toolNames }) {+ const lifecycle = runFileLifecycle.responsesForText(text);+ if (lifecycle) return lifecycle;++ const runFileDelivery = runFileDeliveryResponses(text);+ if (runFileDelivery) return runFileDelivery;+const backgroundCompletion = backgroundCompletionResponses(text);if (backgroundCompletion) {return backgroundCompletion;}+ const runFileVersions = runFileVersionsResponses(text);+ if (runFileVersions) {+ return runFileVersions;+ }++ const runFiles = runFilesResponses(text);+ if (runFiles) {+ return runFiles;+ }+const subagentActivity = subagentActivityResponses(text);if (subagentActivity) {return subagentActivity;@@ -2647,9 +2958,11 @@ module.exports = function fakeModelHook(run, context) {sleep,toolCalls,thrownError,- overrideSubagentModel,+ overrideSubagentModel:+ overrideSubagentModel || runFileLifecycle.isFixtureAgents(context?.agents),disableHumanInTheLoop,resolveInvocation: async (streamMessages, streamOptions, runManager) =>+ runFileLifecycle.resolveInvocation(streamMessages) ??deferredHitlInvocationResponse({graph,messages: streamMessages,diff --git a/e2e/setup/fake-rag-server.js b/e2e/setup/fake-rag-server.jsindex 61af20f93c..20469df2e0 100644--- a/e2e/setup/fake-rag-server.js+++ b/e2e/setup/fake-rag-server.js@@ -93,7 +93,7 @@ async function handleEmbed(req, res) {async function handleQuery(req, res) {const body = await readJson(req);queries.push({ file_id: body.file_id || '', query: body.query || '' });- sendJson(res, 200, { data: [] });+ sendJson(res, 200, []);}async function handleDeleteDocuments(req, res) {diff --git a/e2e/setup/run-files-lifecycle-model.js b/e2e/setup/run-files-lifecycle-model.jsnew file mode 100644index 0000000000..c1cc6bd808--- /dev/null+++ b/e2e/setup/run-files-lifecycle-model.js@@ -0,0 +1,240 @@+const MARKER = 'E2E_RUN_FILES_LIFECYCLE:';+const CHILD_MARKER = 'E2E_RUN_FILES_LIFECYCLE_CHILD:';++/** Provider-boundary scripts; every assertion reads results from real application tools. */+function createRunFileLifecycleResponses({ findLastToolMessage, getContentText, messageType }) {+ const parse = (message) => {+ try {+ return JSON.parse(getContentText(message?.content));+ } catch {+ return null;+ }+ };+ const sameIds = (catalog, ids) =>+ Array.isArray(catalog?.files) &&+ JSON.stringify(catalog.files.map((file) => file.file_id).sort()) ===+ JSON.stringify([...ids].sort());+ const failure = (label, reason, result) => ({+ response: `E2E lifecycle failed ${label}: ${reason}; ${getContentText(result?.content)}`,+ });++ function readScenario(text) {+ const match = text.match(/E2E_RUN_FILES_LIFECYCLE(_CHILD)?:(\{[^\n]*\})/);+ if (!match) return null;+ try {+ const value = JSON.parse(match[2]);+ if (!/^[A-Za-z0-9-]+$/.test(value.label) || typeof value.childId !== 'string') return null;+ return { ...value, child: Boolean(match[1]) };+ } catch {+ return null;+ }+ }++ function resolveScenario(scenario, messages) {+ const { label, childId, mode, phase, inputId } = scenario;+ const callId = (step) => `call_e2e_lifecycle_${label}_${mode}_${phase ?? 'initial'}_${step}`;+ const resultFor = (step) => findLastToolMessage(messages, callId(step));+ const call = (step, name, args = {}, response = '') => ({+ response,+ toolCalls: [{ id: callId(step), name, args, type: 'tool_call' }],+ });+ const write = (step, suffix) =>+ call(step, 'bash_tool', {+ command: `printf 'source,count\\npdf,1\\n' > /mnt/data/e2e-run-files-${label}-${suffix}.csv\n# E2E_RUN_FILE_ARTIFACT:${label}-${suffix}`,+ });+ const artifactFor = (result, suffix) =>+ parse(result)?.artifacts?.find(+ (artifact) => artifact.filename === `e2e-run-files-${label}-${suffix}.csv`,+ );++ if (scenario.child) {+ const inputs = resultFor('inputs');+ if (!inputs) return call('inputs', 'list_run_files');+ if (!sameIds(parse(inputs), mode === 'probe' ? [] : [inputId])) {+ return failure(label, 'child catalog crossed current-turn/run boundaries', inputs);+ }++ if (mode === 'probe' || phase === 'recover') {+ if ((parse(inputs)?.artifacts ?? []).length !== 0) {+ return failure(label, 'new execution restored an unpublished artifact', inputs);+ }+ const stale = resultFor('stale');+ if (!stale) {+ return call('stale', 'publish_artifact', { artifact_id: scenario.artifactId });+ }+ if (+ !getContentText(stale.content).includes(+ 'Only artifacts generated by this execution can be published.',+ ) ||+ parse(stale)?.file_id+ ) {+ return failure(label, 'stale private artifact was not rejected', stale);+ }+ if (mode === 'probe') {+ return { response: `E2E lifecycle rejected ${label}` };+ }+ if (!resultFor('regenerate')) return write('regenerate', 'regenerated');+ const catalog = resultFor('regenerated');+ if (!catalog) return call('regenerated', 'list_run_files');+ const artifact = artifactFor(catalog, 'regenerated');+ if (!artifact || artifact.artifact_id === scenario.artifactId) {+ return failure(label, 'regeneration did not create a new private version', catalog);+ }+ const publication = resultFor('republish');+ if (!publication) {+ return call('republish', 'publish_artifact', { artifact_id: artifact.artifact_id });+ }+ const published = parse(publication);+ if (!published?.file_id || published.file_id === scenario.publishedId) {+ return failure(+ label,+ 'regenerated output did not receive its own durable ID',+ publication,+ );+ }+ return { response: `E2E lifecycle regenerated ${published.file_id}` };+ }++ if (!resultFor('write')) return write('write', mode === 'cancel' ? 'private' : 'published');+ const catalog = resultFor('catalog');+ if (!catalog) return call('catalog', 'list_run_files');+ const artifact = artifactFor(catalog, mode === 'cancel' ? 'private' : 'published');+ if (!artifact?.artifact_id)+ return failure(label, 'output was not privately captured', catalog);+ if (mode === 'cancel') {+ return {+ response: `E2E lifecycle child ${JSON.stringify({ artifactId: artifact.artifact_id })}`,+ };+ }+ const publication = resultFor('publish');+ if (!publication) {+ return call('publish', 'publish_artifact', { artifact_id: artifact.artifact_id });+ }+ const published = parse(publication);+ if (!published?.file_id) return failure(label, 'publication did not persist', publication);+ if (mode === 'concurrent') {+ return {+ response: `E2E lifecycle child ${JSON.stringify({ publishedId: published.file_id })}`,+ };+ }+ if (!resultFor('draft')) return write('draft', 'private');+ const drafts = resultFor('drafts');+ if (!drafts) return call('drafts', 'list_run_files');+ const draft = artifactFor(drafts, 'private');+ if (!draft?.artifact_id || draft.artifact_id === artifact.artifact_id) {+ return failure(label, 'private draft was not retained beside the publication', drafts);+ }+ return {+ response: `E2E lifecycle child ${JSON.stringify({+ publishedId: published.file_id,+ artifactId: draft.artifact_id,+ })}`,+ };+ }++ const child = resultFor('delegate');+ if (!child) {+ return call(+ 'delegate',+ 'subagent',+ { description: `${CHILD_MARKER}${JSON.stringify(scenario)}`, subagent_type: childId },+ mode === 'concurrent'+ ? `E2E lifecycle running ${label} ${Array.from({ length: 250 }, (_, i) => `step-${i}`).join(' ')}\n`+ : '',+ );+ }+ if (mode === 'probe') {+ return getContentText(child.content).includes(`E2E lifecycle rejected ${label}`)+ ? { response: `E2E lifecycle passed probe ${label}` }+ : failure(label, 'child failed to reject the cancelled output', child);+ }+ const proofMatch = getContentText(child.content).match(/E2E lifecycle child (\{[^\n]*\})/);+ if (!proofMatch) return failure(label, 'child produced no artifact proof', child);+ const proof = JSON.parse(proofMatch[1]);+ const parent = resultFor('parent');+ if (!parent) return call('parent', 'list_run_files');+ const expectedIds = proof.publishedId ? [inputId, proof.publishedId] : [inputId];+ if (!sameIds(parse(parent), expectedIds) || (parse(parent)?.artifacts ?? []).length !== 0) {+ return failure(label, 'parent catalog exposed private or unrelated files', parent);+ }+ if (mode === 'concurrent') {+ return {+ response: `E2E lifecycle passed concurrent ${label} file=${proof.publishedId}`,+ };+ }+ if (mode === 'cancel') {+ return {+ response:+ `E2E lifecycle private ${JSON.stringify({ label, ...proof })}\n` ++ Array.from({ length: 2_000 }, (_, i) => `waiting-${i}`).join(' '),+ };+ }++ const answer = resultFor('ask');+ if (!answer) {+ return call(+ 'ask',+ 'ask_user_question',+ {+ questions: [+ {+ id: 'confirmation',+ question: `Resume shared files ${label}?`,+ options: [{ label: `Continue ${label}`, value: `continue-${label}` }],+ },+ ],+ },+ `E2E lifecycle pending ${JSON.stringify({ label, ...proof })}\n` ++ Array.from({ length: 150 }, (_, i) => `preparing-${i}`).join(' '),+ );+ }+ if (!getContentText(answer.content).includes(`continue-${label}`)) {+ return failure(label, 'checkpoint resume lost the user answer', answer);+ }+ const restored = resultFor('restored');+ if (!restored) return call('restored', 'list_run_files');+ if (!sameIds(parse(restored), expectedIds) || (parse(restored)?.artifacts ?? []).length !== 0) {+ return failure(label, 'resume lost the publication or restored a private draft', restored);+ }+ const recovery = resultFor('recover');+ if (!recovery) {+ return call('recover', 'subagent', {+ description: `${CHILD_MARKER}${JSON.stringify({ ...scenario, phase: 'recover', ...proof })}`,+ subagent_type: childId,+ });+ }+ const regeneratedId = getContentText(recovery.content).match(+ /E2E lifecycle regenerated ([\w-]+)/,+ )?.[1];+ if (!regeneratedId) return failure(label, 'resumed child did not regenerate', recovery);+ const final = resultFor('final');+ if (!final) return call('final', 'list_run_files');+ if (!sameIds(parse(final), [...expectedIds, regeneratedId])) {+ return failure(label, 'resumed publication was not visible to the parent', final);+ }+ return {+ response: `E2E lifecycle passed resume ${label} original=${proof.publishedId} regenerated=${regeneratedId}`,+ };+ }++ function resolveInvocation(messages) {+ for (let index = (messages ?? []).length - 1; index >= 0; index--) {+ if (!['human', 'user'].includes(messageType(messages[index]))) continue;+ const scenario = readScenario(getContentText(messages[index].content));+ if (scenario) return resolveScenario(scenario, messages);+ }+ return null;+ }++ return {+ responsesForText: (text) =>+ text.includes(MARKER)+ ? { responses: [''], sleep: 15, overrideSubagentModel: true, resolveInvocation }+ : null,+ resolveInvocation,+ isFixtureAgents: (agents) =>+ (agents ?? []).some((agent) => agent.name?.startsWith('E2E Lifecycle')),+ };+}++module.exports = { createRunFileLifecycleResponses };diff --git a/e2e/setup/run-files-model.js b/e2e/setup/run-files-model.jsnew file mode 100644index 0000000000..881a7f52da--- /dev/null+++ b/e2e/setup/run-files-model.js@@ -0,0 +1,282 @@+const { createHash } = require('crypto');++const DELIVERY = 'E2E_RUN_FILE_DELIVERY:';+const NESTED = 'E2E_RUN_FILE_NESTED:';+const RECIPIENTS = 'E2E_RUN_FILE_RECIPIENTS:';++function contentText(content) {+ if (typeof content === 'string') return content;+ if (!Array.isArray(content)) return '';+ return content.map((part) => (typeof part === 'string' ? part : (part?.text ?? ''))).join('\n');+}++function messageType(message) {+ return message.getType?.() ?? message._getType?.() ?? message.role ?? message.type;+}++function markerValue(text, marker) {+ const index = text.indexOf(marker);+ return index < 0+ ? ''+ : text+ .slice(index + marker.length)+ .trim()+ .split(/\s+/, 1)[0];+}++function childPrompt(messages, marker) {+ return messages.some(+ (message) =>+ ['human', 'user'].includes(messageType(message)) &&+ contentText(message.content).includes(marker),+ );+}++function toolId(label, phase) {+ return `call_e2e_run_file_delivery_${label}_${phase}`;+}++function toolResult(messages, label, phase) {+ return messages.findLast(+ (message) => messageType(message) === 'tool' && message.tool_call_id === toolId(label, phase),+ );+}++function call(label, phase, name, args = {}) {+ return {+ response: '',+ toolCalls: [{ id: toolId(label, phase), name, args, type: 'tool_call' }],+ };+}++function delegate(label, phase, agentId, description) {+ return call(label, phase, 'subagent', { subagent_type: agentId, description });+}++function parsedResult(message) {+ return JSON.parse(contentText(message.content));+}++function requireCatalog(message, fileIds) {+ const catalog = parsedResult(message);+ const actualIds = catalog.files.map((file) => file.file_id).sort();+ if (JSON.stringify(actualIds) !== JSON.stringify([...fileIds].sort())) {+ throw new Error(`Unexpected shared-file catalog: ${JSON.stringify(catalog)}`);+ }+ return catalog;+}++function requireResult(message, expected) {+ const result = contentText(message?.content);+ if (!result.includes(expected)) {+ throw new Error(`Expected ${expected}; received ${result}`);+ }+ return result;+}++function sha256(bytes) {+ return createHash('sha256').update(bytes).digest('hex');+}++function providerDocuments(messages) {+ return messages.flatMap((message) => {+ if (!['human', 'user'].includes(messageType(message)) || !Array.isArray(message.content)) {+ return [];+ }+ return message.content.flatMap((part) => {+ const file = part.type === 'file' ? part.file : part;+ if (part.type !== 'file' && part.type !== 'input_file') return [];+ const encoded = file?.file_data?.match(/^data:application\/pdf;base64,(.+)$/);+ return encoded ? [{ filename: file.filename, bytes: Buffer.from(encoded[1], 'base64') }] : [];+ });+ });+}++function extractedFileText(messages, filename) {+ const heading = `# "${filename}"\n`;+ for (const message of messages) {+ if (!['human', 'user'].includes(messageType(message))) continue;+ const text = contentText(message.content);+ const start = text.indexOf(heading);+ if (start < 0) continue;+ return text+ .slice(start + heading.length)+ .split(/\n```|\n\n---\n\n/, 1)[0]+ .trimEnd();+ }+ throw new Error(`No extracted text for ${filename} reached the child model`);+}++function deliveryResponses(value) {+ const [childId, label, pdfId, textId, pdfHash, textHash] = value.split(':');+ const prompt = `E2E_RUN_FILE_DELIVERY_CHILD:${label}`;+ const complete = `E2E run file delivery verified ${label} pdf=${pdfHash} text=${textHash}`;+ return {+ responses: [''],+ overrideSubagentModel: true,+ resolveInvocation(messages) {+ if (!childPrompt(messages, prompt)) {+ const result = toolResult(messages, label, 'delivery_child');+ if (!result) return delegate(label, 'delivery_child', childId, prompt);+ return { response: requireResult(result, complete) };+ }+ const catalog = toolResult(messages, label, 'delivery_catalog');+ if (!catalog) return call(label, 'delivery_catalog', 'list_run_files');+ requireCatalog(catalog, [pdfId, textId]);+ const documents = providerDocuments(messages);+ const pdfName = `e2e-delivery-${label}.pdf`;+ const textName = `e2e-delivery-${label}.txt`;+ if (documents.length !== 1 || documents[0].filename !== pdfName) {+ throw new Error(`Expected one provider PDF in child messages; got ${documents.length}`);+ }+ const actualPdfHash = sha256(documents[0].bytes);+ const actualTextHash = sha256(extractedFileText(messages, textName));+ if (actualPdfHash !== pdfHash || actualTextHash !== textHash) {+ throw new Error(`Child input bytes differ: pdf=${actualPdfHash} text=${actualTextHash}`);+ }+ return { response: complete };+ },+ };+}++function nestedResponses(value) {+ const [middleId, leafId, outsiderId, label, inputId] = value.split(':');+ const middlePrompt = `E2E_RUN_FILE_NESTED_MIDDLE:${label}`;+ const leafPrompt = `E2E_RUN_FILE_NESTED_LEAF:${label}`;+ const leafComplete = `E2E nested leaf verified ${label} file=${inputId}`;+ const middleComplete = `E2E nested middle verified ${label} file=${inputId}`;+ return {+ responses: [''],+ overrideSubagentModel: true,+ resolveInvocation(messages) {+ if (childPrompt(messages, leafPrompt)) {+ const catalog = toolResult(messages, label, 'leaf_catalog');+ if (!catalog) return call(label, 'leaf_catalog', 'list_run_files');+ const evidence = {+ toolCallId: catalog.tool_call_id,+ catalog: requireCatalog(catalog, [inputId]),+ };+ return { response: `${leafComplete}\nE2E_LEAF_CATALOG:${JSON.stringify(evidence)}` };+ }+ if (childPrompt(messages, middlePrompt)) {+ const catalog = toolResult(messages, label, 'middle_catalog');+ if (!catalog) return call(label, 'middle_catalog', 'list_run_files');+ requireCatalog(catalog, [inputId]);+ const result = toolResult(messages, label, 'leaf_child');+ if (!result) return delegate(label, 'leaf_child', leafId, leafPrompt);+ requireResult(result, leafComplete);+ return { response: middleComplete };+ }+ const rejected = toolResult(messages, label, 'outsider_child');+ if (!rejected) {+ return delegate(label, 'outsider_child', outsiderId, `E2E_UNAUTHORIZED_CHILD:${label}`);+ }+ requireResult(rejected, 'Received tool input did not match expected schema');+ const result = toolResult(messages, label, 'middle_child');+ if (!result) return delegate(label, 'middle_child', middleId, middlePrompt);+ requireResult(result, middleComplete);+ return { response: `E2E nested sharing complete ${label} file=${inputId}` };+ },+ };+}++function recipientResponses(value) {+ const [producerId, readerId, observerId, outsiderId, label, inputId] = value.split(':');+ const producerPrompt = `E2E_RUN_FILE_PRODUCER:${label}`;+ const readerPrompt = `E2E_RUN_FILE_READER:${label}`;+ const observerPrompt = `E2E_RUN_FILE_OBSERVER:${label}`;+ const outputName = `e2e-run-files-${label}.csv`;+ return {+ responses: [''],+ overrideSubagentModel: true,+ resolveInvocation(messages) {+ if (childPrompt(messages, producerPrompt)) {+ const inputCatalog = toolResult(messages, label, 'producer_inputs');+ if (!inputCatalog) return call(label, 'producer_inputs', 'list_run_files');+ requireCatalog(inputCatalog, [inputId]);+ const write = toolResult(messages, label, 'producer_write');+ if (!write) {+ return call(label, 'producer_write', 'bash_tool', {+ command: `echo E2E_RUN_FILE_ARTIFACT:${label}`,+ });+ }+ const privateCatalog = toolResult(messages, label, 'producer_private');+ if (!privateCatalog) return call(label, 'producer_private', 'list_run_files');+ const artifact = requireCatalog(privateCatalog, [inputId]).artifacts.find(+ (entry) => entry.filename === outputName,+ );+ if (!artifact) throw new Error('Producer output has no private artifact ID');+ const rejected = toolResult(messages, label, 'publish_outsider');+ if (!rejected) {+ return call(label, 'publish_outsider', 'publish_artifact', {+ artifact_id: artifact.artifact_id,+ recipient_agent_ids: [outsiderId],+ });+ }+ requireResult(rejected, 'sharing policy does not authorize');+ const retryCatalog = toolResult(messages, label, 'producer_retry');+ if (!retryCatalog) return call(label, 'producer_retry', 'list_run_files');+ const retained = requireCatalog(retryCatalog, [inputId]).artifacts;+ if (!retained.some((entry) => entry.artifact_id === artifact.artifact_id)) {+ throw new Error('Rejected recipients consumed the private artifact');+ }+ const published = toolResult(messages, label, 'publish_reader');+ if (!published) {+ return call(label, 'publish_reader', 'publish_artifact', {+ artifact_id: artifact.artifact_id,+ recipient_agent_ids: [readerId],+ });+ }+ const file = parsedResult(published);+ if (!file.file_id || file.filename !== outputName) {+ throw new Error('Publication did not return the durable output identity');+ }+ return { response: `E2E recipient publication ${label} file=${file.file_id}` };+ }+ if (childPrompt(messages, observerPrompt)) {+ const catalog = toolResult(messages, label, 'observer_catalog');+ if (!catalog) return call(label, 'observer_catalog', 'list_run_files');+ const observed = requireCatalog(catalog, [inputId]);+ if (observed.artifacts.length !== 0) throw new Error('Observer can see private artifacts');+ return { response: `E2E observer isolated ${label}` };+ }+ if (childPrompt(messages, readerPrompt)) {+ const catalog = toolResult(messages, label, 'reader_catalog');+ if (!catalog) return call(label, 'reader_catalog', 'list_run_files');+ const files = parsedResult(catalog).files;+ const file = files.find((entry) => entry.filename === outputName);+ if (!file) throw new Error('Named sibling recipient cannot see the publication');+ requireCatalog(catalog, [inputId, file.file_id]);+ const search = toolResult(messages, label, 'reader_search');+ if (!search) return call(label, 'reader_search', 'file_search', { query: outputName });+ requireResult(search, 'No content found in the files.');+ return { response: `E2E reader searched ${label} file=${file.file_id}` };+ }+ const produced = toolResult(messages, label, 'producer_child');+ if (!produced) return delegate(label, 'producer_child', producerId, producerPrompt);+ const fileId = contentText(produced.content).match(/file=([\w-]+)/)?.[1];+ if (!fileId) throw new Error('Producer returned no published file ID');+ const observer = toolResult(messages, label, 'observer_child');+ if (!observer) return delegate(label, 'observer_child', observerId, observerPrompt);+ requireResult(observer, `E2E observer isolated ${label}`);+ const reader = toolResult(messages, label, 'reader_child');+ if (!reader) return delegate(label, 'reader_child', readerId, readerPrompt);+ requireResult(reader, `E2E reader searched ${label} file=${fileId}`);+ const catalog = toolResult(messages, label, 'recipient_parent_catalog');+ if (!catalog) return call(label, 'recipient_parent_catalog', 'list_run_files');+ requireCatalog(catalog, [inputId, fileId]);+ return { response: `E2E recipient sharing complete ${label} file=${fileId}` };+ },+ };+}++function runFileDeliveryResponses(text) {+ const delivery = markerValue(text, DELIVERY);+ if (delivery) return deliveryResponses(delivery);+ const nested = markerValue(text, NESTED);+ if (nested) return nestedResponses(nested);+ const recipients = markerValue(text, RECIPIENTS);+ return recipients ? recipientResponses(recipients) : null;+}++module.exports = { runFileDeliveryResponses };diff --git a/e2e/specs/mock/deployment-skills.spec.ts b/e2e/specs/mock/deployment-skills.spec.tsindex c5c98e2926..769020ab87 100644--- a/e2e/specs/mock/deployment-skills.spec.ts+++ b/e2e/specs/mock/deployment-skills.spec.ts@@ -1,3 +1,5 @@+import fs from 'node:fs';+import path from 'node:path';import { expect, test } from '@playwright/test';import type { Page } from '@playwright/test';import { NEW_CHAT_PATH } from './helpers';@@ -138,6 +140,14 @@ test.describe('deployment skills', () => {test('loads configured deployment skills for every authenticated user as read-only', async ({page,}) => {+ const fixture = fs.readFileSync(+ path.resolve(+ __dirname,+ '../../fixtures/deployment-skills',+ DEPLOYMENT_SKILL_NAME,+ 'guide.txt',+ ),+ );await page.goto(NEW_CHAT_PATH, { timeout: 10000 });const token = await getAccessToken(page);@@ -181,7 +191,7 @@ test.describe('deployment skills', () => {filename: 'guide.txt',source: 'deployment',mimeType: 'text/plain',- bytes: 'deployment skill file fixture\n'.length,+ bytes: fixture.length,category: 'other',isExecutable: false,});@@ -196,9 +206,9 @@ test.describe('deployment skills', () => {relativePath: 'guide.txt',filename: 'guide.txt',mimeType: 'text/plain',- bytes: 'deployment skill file fixture\n'.length,+ bytes: fixture.length,isBinary: false,- content: 'deployment skill file fixture\n',+ content: fixture.toString('utf8'),});const patch = await apiJson<{ message?: string }>(diff --git a/e2e/specs/mock/run-files-delivery.spec.ts b/e2e/specs/mock/run-files-delivery.spec.tsnew file mode 100644index 0000000000..77d5d04a9c--- /dev/null+++ b/e2e/specs/mock/run-files-delivery.spec.ts@@ -0,0 +1,372 @@+import { expect, test } from '@playwright/test';+import { createHash, randomUUID } from 'node:crypto';+import { ContentTypes, FileContext } from 'librechat-data-provider';+import type { Agents, TFile, TMessage } from 'librechat-data-provider';+import type { Page } from '@playwright/test';+import type { AgentDetail } from './agents.helpers';+import {+ fetchJson,+ uniqueName,+ RAG_API_BASE,+ messagesView,+ requestJson,+ getAccessToken,+ getRagEmbedded,+ resetProvisioning,+ uploadViaUnifiedButton,+ getCodeProvisionedUploads,+ sendMessageAndWaitForCompletion,+} from './helpers';+import { cleanupAgent, openAgentBuilder, uniqueAgentName } from './agents.helpers';++type Catalog = {+ files: Array<{ file_id: string; filename: string }>;+ artifacts: Array<{ artifact_id: string; filename: string }>;+};++type PersistedToolCall = Agents.ToolCall & {+ subagent_content?: NonNullable<TMessage['content']>;+};++function inputPdf(text: string): string {+ const content = `BT /F1 12 Tf 72 720 Td (${text}) Tj ET`;+ const objects = [+ '<< /Type /Catalog /Pages 2 0 R >>',+ '<< /Type /Pages /Kids [3 0 R] /Count 1 >>',+ '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>',+ `<< /Length ${Buffer.byteLength(content)} >>\nstream\n${content}\nendstream`,+ '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>',+ ];+ let pdf = '%PDF-1.4\n';+ const offsets: number[] = [];+ for (let index = 0; index < objects.length; index++) {+ offsets.push(Buffer.byteLength(pdf));+ pdf += `${index + 1} 0 obj\n${objects[index]}\nendobj\n`;+ }+ const xrefOffset = Buffer.byteLength(pdf);+ pdf += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;+ pdf += offsets.map((offset) => `${String(offset).padStart(10, '0')} 00000 n \n`).join('');+ return `${pdf}trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xrefOffset}\n%%EOF\n`;+}++function sha256(content: string): string {+ return createHash('sha256').update(content).digest('hex');+}++async function createAgent(+ page: Page,+ token: string,+ agents: AgentDetail[],+ fields: Pick<AgentDetail, 'tools' | 'subagents'> = {},+): Promise<AgentDetail> {+ const agent = await requestJson<AgentDetail>(page, {+ path: '/api/agents',+ token,+ method: 'POST',+ body: {+ name: uniqueAgentName('E2E Run File Delivery'),+ description: 'Shared-file delivery and authorization integration fixture.',+ instructions: 'Follow the test request exactly.',+ provider: 'Mock Run Files',+ model: 'mock-run-files',+ ...fields,+ },+ });+ agents.push(agent);+ return agent;+}++async function selectAgent(page: Page, agent: AgentDetail): Promise<void> {+ const form = await openAgentBuilder(page);+ await form.getByRole('combobox', { name: 'Agent', exact: true }).click();+ await page.getByRole('option', { name: agent.name, exact: true }).click();+ await expect(form.getByLabel('Agent name')).toHaveValue(agent.name ?? '');+ await form.getByRole('button', { name: 'Select Agent' }).click();+}++async function upload(+ page: Page,+ files: TFile[],+ name: string,+ mimeType: string,+ content: string,+): Promise<TFile> {+ const response = await uploadViaUnifiedButton(page, { name, mimeType, content });+ expect(response.ok()).toBeTruthy();+ const file = (await response.json()) as TFile;+ expect(file.file_id).toBeTruthy();+ files.push(file);+ return file;+}++async function cleanup(page: Page, agents: AgentDetail[], files: TFile[]): Promise<void> {+ if (files.length > 0) {+ await requestJson(page, {+ path: '/api/files',+ token: await getAccessToken(page),+ method: 'DELETE',+ body: { files },+ });+ }+ for (const agent of [...agents].reverse()) await cleanupAgent(page, agent.id);+}++function toolCalls(messages: TMessage[]): PersistedToolCall[] {+ const calls: PersistedToolCall[] = [];+ const visit = (content: NonNullable<TMessage['content']>): void => {+ for (const part of content) {+ if (part?.type === ContentTypes.TOOL_CALL && 'tool_call' in part) {+ const call = part.tool_call as PersistedToolCall;+ calls.push(call);+ if (Array.isArray(call.subagent_content)) visit(call.subagent_content);+ }+ }+ };+ for (const message of messages) visit(message.content ?? []);+ return calls;+}++function output(messages: TMessage[], label: string, phase: string): string {+ const id = `call_e2e_run_file_delivery_${label}_${phase}`;+ const result = toolCalls(messages).find((call) => call.id === id)?.output;+ expect(result, `Expected persisted output for ${phase}`).toBeDefined();+ return result ?? '';+}++function catalog(messages: TMessage[], label: string, phase: string): Catalog {+ return JSON.parse(output(messages, label, phase)) as Catalog;+}++async function loadMessages(page: Page, conversationId: string): Promise<TMessage[]> {+ return fetchJson<TMessage[]>(+ page,+ `/api/messages/${encodeURIComponent(conversationId)}`,+ await getAccessToken(page),+ );+}++test.describe('run-file delivery and authorization', () => {+ test('delivers native PDF bytes and extracted text to the child without eager tool provisioning', async ({+ page,+ }) => {+ test.setTimeout(120_000);+ const label = uniqueName('delivery');+ const files: TFile[] = [];+ const agents: AgentDetail[] = [];+ try {+ await page.goto('/c/new');+ const token = await getAccessToken(page);+ const child = await createAgent(page, token, agents, {+ tools: ['execute_code', 'file_search'],+ });+ const parent = await createAgent(page, token, agents, {+ subagents: { enabled: true, allowSelf: false, shareFiles: true, agent_ids: [child.id] },+ });+ await selectAgent(page, parent);+ await resetProvisioning(page);+ const pdfBytes = inputPdf(`E2E PDF canary ${randomUUID()}`);+ const textBytes = `E2E extracted text canary ${randomUUID()}`;+ const pdf = await upload(+ page,+ files,+ `e2e-delivery-${label}.pdf`,+ 'application/pdf',+ pdfBytes,+ );+ const text = await upload(page, files, `e2e-delivery-${label}.txt`, 'text/plain', textBytes);+ expect(pdf.llmDeliveryPath).toBe('provider');+ expect(text.llmDeliveryPath).toBe('text');+ const pdfHash = sha256(pdfBytes);+ const textHash = sha256(textBytes);+ const admission = await sendMessageAndWaitForCompletion(+ page,+ `E2E_RUN_FILE_DELIVERY:${child.id}:${label}:${pdf.file_id}:${text.file_id}:${pdfHash}:${textHash}`,+ { timeout: 60_000 },+ );+ const { conversationId } = (await admission.json()) as { conversationId: string };+ const complete = `E2E run file delivery verified ${label} pdf=${pdfHash} text=${textHash}`;+ await expect(messagesView(page)).toContainText(complete);+ const messages = await loadMessages(page, conversationId);+ expect(output(messages, label, 'delivery_child')).toContain(complete);+ expect(+ catalog(messages, label, 'delivery_catalog')+ .files.map((file) => file.file_id)+ .sort(),+ ).toEqual([pdf.file_id, text.file_id].sort());+ expect(+ toolCalls(messages)+ .map((call) => call.name)+ .sort(),+ ).toEqual(['list_run_files', 'subagent']);+ expect(await getCodeProvisionedUploads(page)).toEqual([]);+ expect(await getRagEmbedded(page)).toEqual([]);+ await page.reload();+ await expect(messagesView(page)).toContainText(complete);+ } finally {+ await cleanup(page, agents, files);+ }+ });++ test('authorizes a nested child for current files and rejects an agent outside the roster', async ({+ page,+ }) => {+ test.setTimeout(180_000);+ const label = uniqueName('nested');+ const files: TFile[] = [];+ const agents: AgentDetail[] = [];+ try {+ await page.goto('/c/new');+ const token = await getAccessToken(page);+ const leaf = await createAgent(page, token, agents);+ const outsider = await createAgent(page, token, agents);+ const middle = await createAgent(page, token, agents, {+ subagents: { enabled: true, allowSelf: false, shareFiles: true, agent_ids: [leaf.id] },+ });+ const parent = await createAgent(page, token, agents, {+ subagents: { enabled: true, allowSelf: false, shareFiles: true, agent_ids: [middle.id] },+ });+ await selectAgent(page, parent);+ const previous = await upload(+ page,+ files,+ `e2e-previous-${label}.csv`,+ 'text/csv',+ 'scope,value\nprevious,secret\n',+ );+ await sendMessageAndWaitForCompletion(page, `E2E_REPLY:previous-${label}`);+ const current = await upload(+ page,+ files,+ `e2e-current-${label}.csv`,+ 'text/csv',+ 'scope,value\ncurrent,authorized\n',+ );+ const admission = await sendMessageAndWaitForCompletion(+ page,+ `E2E_RUN_FILE_NESTED:${middle.id}:${leaf.id}:${outsider.id}:${label}:${current.file_id}`,+ { timeout: 90_000 },+ );+ const { conversationId } = (await admission.json()) as { conversationId: string };+ await expect(messagesView(page)).toContainText(+ `E2E nested sharing complete ${label} file=${current.file_id}`,+ );+ const messages = await loadMessages(page, conversationId);+ const leafResult = output(messages, label, 'leaf_child');+ expect(leafResult).toContain(`E2E nested leaf verified ${label} file=${current.file_id}`);+ const encodedEvidence = leafResult.match(/E2E_LEAF_CATALOG:(.+)/)?.[1];+ expect(encodedEvidence, 'Leaf must return its actual catalog tool result').toBeDefined();+ if (!encodedEvidence) throw new Error('Nested catalog evidence missing');+ const leafEvidence = JSON.parse(encodedEvidence) as { toolCallId: string; catalog: Catalog };+ expect(leafEvidence.toolCallId).toBe(`call_e2e_run_file_delivery_${label}_leaf_catalog`);+ for (const observed of [catalog(messages, label, 'middle_catalog'), leafEvidence.catalog]) {+ const ids = observed.files.map((file) => file.file_id);+ expect(ids).toEqual([current.file_id]);+ expect(ids).not.toContain(previous.file_id);+ }+ const rejected = toolCalls(messages).find(+ (call) => call.id === `call_e2e_run_file_delivery_${label}_outsider_child`,+ );+ expect(output(messages, label, 'outsider_child')).toContain(+ 'Received tool input did not match expected schema',+ );+ expect(JSON.parse(String(rejected?.args))).toMatchObject({ subagent_type: outsider.id });+ expect(rejected?.subagent_content).toBeUndefined();+ const delegated = toolCalls(messages).find(+ (call) => call.id === `call_e2e_run_file_delivery_${label}_leaf_child`,+ );+ expect(JSON.parse(String(delegated?.args))).toMatchObject({ subagent_type: leaf.id });+ } finally {+ await cleanup(page, agents, files);+ }+ });++ test('grants a published file only to its named sibling and allows that sibling to search it', async ({+ page,+ }) => {+ test.setTimeout(180_000);+ const label = uniqueName('recipients');+ const files: TFile[] = [];+ const agents: AgentDetail[] = [];+ try {+ await page.goto('/c/new');+ const token = await getAccessToken(page);+ const producer = await createAgent(page, token, agents, { tools: ['execute_code'] });+ const reader = await createAgent(page, token, agents, { tools: ['file_search'] });+ const observer = await createAgent(page, token, agents);+ const outsider = await createAgent(page, token, agents);+ const parent = await createAgent(page, token, agents, {+ subagents: {+ enabled: true,+ allowSelf: false,+ shareFiles: true,+ agent_ids: [producer.id, reader.id, observer.id],+ },+ });+ await selectAgent(page, parent);+ await resetProvisioning(page);+ const input = await upload(+ page,+ files,+ `e2e-recipient-input-${label}.csv`,+ 'text/csv',+ 'source,count\npdf,1\n',+ );+ const admission = await sendMessageAndWaitForCompletion(+ page,+ `E2E_RUN_FILE_RECIPIENTS:${producer.id}:${reader.id}:${observer.id}:${outsider.id}:${label}:${input.file_id}`,+ { timeout: 120_000 },+ );+ const { conversationId } = (await admission.json()) as { conversationId: string };+ const durableFiles = await fetchJson<TFile[]>(page, '/api/files', token);+ const published = durableFiles.filter(+ (file) =>+ file.conversationId === conversationId && file.context === FileContext.run_artifact,+ );+ files.push(...published);+ expect(published).toHaveLength(1);+ const file = published[0];+ expect(file.metadata?.runFile).toMatchObject({+ agentId: producer.id,+ parentAgentId: parent.id,+ recipientAgentIds: [reader.id],+ inputFileIds: [input.file_id],+ });+ await expect(messagesView(page)).toContainText(+ `E2E recipient sharing complete ${label} file=${file.file_id}`,+ );+ const messages = await loadMessages(page, conversationId);+ expect(output(messages, label, 'publish_outsider')).toContain(+ 'sharing policy does not authorize',+ );+ const beforeRejection = catalog(messages, label, 'producer_private').artifacts;+ expect(catalog(messages, label, 'producer_retry').artifacts).toEqual(beforeRejection);+ expect(beforeRejection).toHaveLength(1);+ expect(catalog(messages, label, 'observer_catalog')).toMatchObject({+ files: [{ file_id: input.file_id }],+ artifacts: [],+ });+ expect(+ catalog(messages, label, 'reader_catalog')+ .files.map((entry) => entry.file_id)+ .sort(),+ ).toEqual([input.file_id, file.file_id].sort());+ expect(output(messages, label, 'reader_search')).toContain('No content found in the files.');+ expect((await getRagEmbedded(page)).map((entry) => entry.file_id)).toContain(file.file_id);+ const queryResponse = await page.request.get(`${RAG_API_BASE}/__debug/embedded`);+ expect(queryResponse.ok()).toBeTruthy();+ const { queries } = (await queryResponse.json()) as {+ queries: Array<{ file_id: string; query: string }>;+ };+ expect(queries).toContainEqual({ file_id: file.file_id, query: file.filename });+ expect(+ messages.some((message) =>+ message.attachments?.some((attachment) =>+ 'file_id' in attachment ? attachment.file_id === file.file_id : false,+ ),+ ),+ ).toBe(true);+ } finally {+ await cleanup(page, agents, files);+ }+ });+});diff --git a/e2e/specs/mock/run-files-lifecycle.spec.ts b/e2e/specs/mock/run-files-lifecycle.spec.tsnew file mode 100644index 0000000000..c930f93e21--- /dev/null+++ b/e2e/specs/mock/run-files-lifecycle.spec.ts@@ -0,0 +1,374 @@+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { readFile, readdir } from 'node:fs/promises';+import { expect, test } from '@playwright/test';+import { FileContext } from 'librechat-data-provider';+import type { TFile, TMessage } from 'librechat-data-provider';+import type { Page, Request } from '@playwright/test';+import type { AgentDetail } from './agents.helpers';+import { cleanupAgent, openAgentBuilder, uniqueAgentName } from './agents.helpers';+import {+ MOCK_ENDPOINTS,+ fetchJson,+ uniqueName,+ sendMessage,+ messagesView,+ requestJson,+ getAccessToken,+ uploadViaUnifiedButton,+ sendMessageAndWaitForCompletion,+} from './helpers';++type LifecycleProof = { label: string; artifactId: string; publishedId?: string };+type LifecycleMode = 'concurrent' | 'cancel' | 'resume' | 'probe';+type GenerationStart = { conversationId: string };++const prompt = (+ mode: LifecycleMode,+ childId: string,+ label: string,+ inputId?: string,+ artifactId?: string,+) => `E2E_RUN_FILES_LIFECYCLE:${JSON.stringify({ mode, childId, label, inputId, artifactId })}`;++async function createAgents(page: Page) {+ const token = await getAccessToken(page);+ const create = (name: string, fields: Pick<AgentDetail, 'tools' | 'subagents'>) =>+ requestJson<AgentDetail>(page, {+ path: '/api/agents',+ token,+ method: 'POST',+ body: {+ name,+ instructions: 'Follow the lifecycle test request exactly.',+ provider: MOCK_ENDPOINTS[1].label,+ model: MOCK_ENDPOINTS[1].model,+ ...fields,+ },+ });+ const child = await create(uniqueAgentName('E2E Lifecycle Child'), { tools: ['execute_code'] });+ const parent = await create(uniqueAgentName('E2E Lifecycle Parent'), {+ tools: ['ask_user_question'],+ subagents: { enabled: true, allowSelf: false, shareFiles: true, agent_ids: [child.id] },+ });+ return { parent, child };+}++async function selectAgent(page: Page, name: string) {+ const form = await openAgentBuilder(page);+ await form.getByRole('combobox', { name: 'Agent', exact: true }).click();+ await page.getByRole('option', { name }).click();+ await expect(form.getByLabel('Agent name')).toHaveValue(name);+ await form.getByRole('button', { name: 'Select Agent' }).click();+}++async function uploadInput(page: Page, label: string): Promise<TFile> {+ const response = await uploadViaUnifiedButton(page, {+ name: `e2e-lifecycle-${label}.csv`,+ mimeType: 'text/csv',+ content: `scope,value\n${label},1\n`,+ });+ expect(response.ok()).toBeTruthy();+ return (await response.json()) as TFile;+}++async function publishedFiles(page: Page, conversationId: string): Promise<TFile[]> {+ const files = await fetchJson<TFile[]>(page, '/api/files', await getAccessToken(page));+ return files.filter(+ (file) => file.context === FileContext.run_artifact && file.conversationId === conversationId,+ );+}++async function waitForCompletion(page: Page, conversationId: string, text: string) {+ await expect(messagesView(page)).toContainText(text, { timeout: 60_000 });+ await expect(page.getByRole('button', { name: 'Stop generating' })).toBeHidden();+ const token = await getAccessToken(page);+ await expect+ .poll(async () => {+ const messages = await fetchJson<TMessage[]>(+ page,+ `/api/messages/${encodeURIComponent(conversationId)}`,+ token,+ );+ const assistant = messages.filter((message) => message.isCreatedByUser === false);+ return (+ assistant.length > 0 &&+ assistant.every((message) => message.unfinished === false && message.error !== true)+ );+ })+ .toBe(true);+}++async function snapshotDirectories(): Promise<string[]> {+ const entries = await readdir(tmpdir(), { withFileTypes: true });+ return entries+ .filter(+ (entry) => entry.isDirectory() && /^librechat-run-files-[A-Za-z0-9]{6}$/.test(entry.name),+ )+ .map((entry) => join(tmpdir(), entry.name));+}++async function newSnapshotDirectories(before: ReadonlySet<string>): Promise<string[]> {+ return (await snapshotDirectories()).filter((directory) => !before.has(directory));+}++async function waitForPrivateSnapshot(before: ReadonlySet<string>): Promise<string[]> {+ let directories: string[] = [];+ await expect+ .poll(async () => {+ directories = await newSnapshotDirectories(before);+ return directories.length;+ })+ .toBe(1);+ const snapshots = await readdir(directories[0]);+ expect(snapshots).toHaveLength(1);+ expect(await readFile(join(directories[0], snapshots[0]), 'utf8')).toBe('source,count\npdf,1\n');+ return directories;+}++async function expectSnapshotsRemoved(directories: string[]) {+ await expect+ .poll(async () => {+ const existing = new Set(await snapshotDirectories());+ return directories.filter((directory) => existing.has(directory));+ })+ .toEqual([]);+}++async function readProof(page: Page, state: 'private' | 'pending'): Promise<LifecycleProof> {+ const pattern = new RegExp(`E2E lifecycle ${state} (\\{[^\\n]*\\})`);+ await expect(messagesView(page)).toContainText(pattern, { timeout: 45_000 });+ const match = (await messagesView(page).innerText()).match(pattern);+ expect(match).not.toBeNull();+ return JSON.parse(match![1]) as LifecycleProof;+}++async function stopGeneration(page: Page) {+ const stop = page.getByRole('button', { name: 'Stop generating' });+ if (!(await stop.isVisible())) return;+ await Promise.all([+ page.waitForResponse(+ (response) =>+ response.request().method() === 'POST' &&+ new URL(response.url()).pathname === '/api/agents/chat/abort',+ ),+ stop.click(),+ ]);+ await expect(stop).toBeHidden({ timeout: 20_000 });+}++async function cleanup(page: Page, agents: string[], files: TFile[]) {+ await stopGeneration(page);+ if (files.length > 0) {+ await requestJson(page, {+ path: '/api/files',+ token: await getAccessToken(page),+ method: 'DELETE',+ body: { files },+ });+ }+ for (const agent of agents) await cleanupAgent(page, agent);+}++async function downloadFile(page: Page, file: TFile) {+ const download = page.waitForEvent('download');+ await messagesView(page)+ .getByRole('button', { name: `Download ${file.filename}`, exact: true })+ .click();+ const result = await download;+ expect(await result.failure()).toBeNull();+ expect(result.suggestedFilename()).toBe(file.filename);+ expect(await readFile(await result.path(), 'utf8')).toBe('source,count\npdf,1\n');+}++function isResumeRequest(request: Request) {+ return (+ request.method() === 'POST' && new URL(request.url()).pathname === '/api/agents/chat/resume'+ );+}++test.describe('run-file lifecycle', () => {+ test('isolates two overlapping runs of the same parent and child agents', async ({+ page,+ browser,+ baseURL,+ }) => {+ test.setTimeout(180_000);+ const secondContext = await browser.newContext({+ baseURL,+ storageState: await page.context().storageState(),+ });+ const second = await secondContext.newPage();+ const files: TFile[] = [];+ const agents: string[] = [];+ try {+ await page.goto('/c/new');+ const { parent, child } = await createAgents(page);+ agents.push(parent.id, child.id);+ const labels = [uniqueName('parallel-a'), uniqueName('parallel-b')];+ await selectAgent(page, parent.name!);+ files.push(await uploadInput(page, labels[0]));+ await selectAgent(second, parent.name!);+ files.push(await uploadInput(second, labels[1]));+ const admissions = [+ await sendMessage(page, prompt('concurrent', child.id, labels[0], files[0].file_id)),+ await sendMessage(second, prompt('concurrent', child.id, labels[1], files[1].file_id)),+ ];+ const starts = (await Promise.all(+ admissions.map((response) => response.json()),+ )) as Array<GenerationStart>;+ expect(starts[0].conversationId).not.toBe(starts[1].conversationId);+ const token = await getAccessToken(page);+ const active = await Promise.all(+ starts.map(({ conversationId }) =>+ fetchJson<{ active: boolean }>(+ page,+ `/api/agents/chat/status/${encodeURIComponent(conversationId)}`,+ token,+ ),+ ),+ );+ expect(active.map((status) => status.active)).toEqual([true, true]);+ await Promise.all(+ [page, second].map((current, index) =>+ waitForCompletion(+ current,+ starts[index].conversationId,+ `E2E lifecycle passed concurrent ${labels[index]}`,+ ),+ ),+ );+ const publications: TFile[] = [];+ for (const [index, current] of [page, second].entries()) {+ const outputs = await publishedFiles(current, starts[index].conversationId);+ files.push(...outputs);+ expect(outputs).toHaveLength(1);+ publications.push(outputs[0]);+ expect(outputs[0].metadata?.runFile).toMatchObject({+ agentId: child.id,+ parentAgentId: parent.id,+ inputFileIds: [files[index].file_id],+ });+ await current.reload();+ await expect(messagesView(current)).toContainText(+ `E2E lifecycle passed concurrent ${labels[index]}`,+ );+ await downloadFile(current, outputs[0]);+ }+ expect(publications[0].metadata?.runFile?.runId).not.toBe(+ publications[1].metadata?.runFile?.runId,+ );+ expect(publications[0].metadata?.runFile?.executionId).not.toBe(+ publications[1].metadata?.runFile?.executionId,+ );+ } finally {+ await stopGeneration(second);+ await secondContext.close();+ await cleanup(page, agents, files);+ }+ });++ test('cancellation deletes private snapshots and a later turn cannot publish their IDs', async ({+ page,+ }) => {+ test.setTimeout(150_000);+ const label = uniqueName('cancelled');+ const files: TFile[] = [];+ const agents: string[] = [];+ try {+ await page.goto('/c/new');+ const { parent, child } = await createAgents(page);+ agents.push(parent.id, child.id);+ await selectAgent(page, parent.name!);+ const input = await uploadInput(page, label);+ files.push(input);+ const before = new Set(await snapshotDirectories());+ const admission = await sendMessage(page, prompt('cancel', child.id, label, input.file_id));+ const { conversationId } = (await admission.json()) as GenerationStart;+ const proof = await readProof(page, 'private');+ expect(proof.label).toBe(label);+ expect(proof.artifactId).toBeTruthy();+ const directories = await waitForPrivateSnapshot(before);+ expect(await publishedFiles(page, conversationId)).toEqual([]);+ await stopGeneration(page);+ await expectSnapshotsRemoved(directories);+ expect(await publishedFiles(page, conversationId)).toEqual([]);+ await page.reload();+ await sendMessageAndWaitForCompletion(+ page,+ prompt('probe', child.id, label, undefined, proof.artifactId),+ { timeout: 60_000 },+ );+ await expect(messagesView(page)).toContainText(`E2E lifecycle passed probe ${label}`);+ expect(await publishedFiles(page, conversationId)).toEqual([]);+ await expectSnapshotsRemoved(directories);+ } finally {+ await cleanup(page, agents, files);+ }+ });++ test('a checkpoint resume restores publications and requires private outputs to be regenerated', async ({+ page,+ }) => {+ test.setTimeout(180_000);+ const label = uniqueName('resumed');+ const files: TFile[] = [];+ const agents: string[] = [];+ try {+ await page.goto('/c/new');+ const { parent, child } = await createAgents(page);+ agents.push(parent.id, child.id);+ await selectAgent(page, parent.name!);+ const input = await uploadInput(page, label);+ files.push(input);+ const before = new Set(await snapshotDirectories());+ const admission = await sendMessage(page, prompt('resume', child.id, label, input.file_id));+ const { conversationId } = (await admission.json()) as GenerationStart;+ const proof = await readProof(page, 'pending');+ expect(proof.label).toBe(label);+ expect(proof.artifactId).toBeTruthy();+ expect(proof.publishedId).toBeTruthy();+ const directories = await waitForPrivateSnapshot(before);+ const question = page+ .getByRole('paragraph')+ .filter({ hasText: `Resume shared files ${label}?` });+ await expect(question).toBeVisible({ timeout: 30_000 });+ await expectSnapshotsRemoved(directories);+ const initial = await publishedFiles(page, conversationId);+ files.push(...initial);+ expect(initial.map((file) => file.file_id)).toEqual([proof.publishedId]);+ await page.reload({ waitUntil: 'domcontentloaded' });+ await expect(question).toBeVisible({ timeout: 30_000 });+ await downloadFile(page, initial[0]);+ await page.getByRole('button', { name: new RegExp(`Continue ${label}$`) }).click();+ const [request, response] = await Promise.all([+ page.waitForRequest(isResumeRequest),+ page.waitForResponse((candidate) => isResumeRequest(candidate.request())),+ page.getByRole('button', { name: 'Submit', exact: true }).click(),+ ]);+ expect(response.ok()).toBeTruthy();+ expect(request.postDataJSON()).toMatchObject({+ conversationId,+ agent_id: parent.id,+ answers: { confirmation: `continue-${label}` },+ });+ await waitForCompletion(page, conversationId, `E2E lifecycle passed resume ${label}`);+ const completed = await publishedFiles(page, conversationId);+ const regenerated = completed.filter((file) => file.file_id !== proof.publishedId);+ files.push(...regenerated);+ expect(completed).toHaveLength(2);+ expect(regenerated).toHaveLength(1);+ expect(regenerated[0].metadata?.runFile?.runId).toBe(initial[0].metadata?.runFile?.runId);+ expect(regenerated[0].metadata?.runFile?.sourceFileId).not.toBe(proof.artifactId);+ expect(regenerated[0].metadata?.runFile?.inputFileIds).toEqual([input.file_id]);+ expect(regenerated[0].metadata?.runFile?.agentId).toBe(child.id);+ await page.reload();+ await expect(messagesView(page)).toContainText(`E2E lifecycle passed resume ${label}`);+ await downloadFile(page, initial[0]);+ await downloadFile(page, regenerated[0]);+ await expectSnapshotsRemoved(directories);+ } finally {+ await cleanup(page, agents, files);+ }+ });+});diff --git a/e2e/specs/mock/run-files.spec.ts b/e2e/specs/mock/run-files.spec.tsnew file mode 100644index 0000000000..c3a47fa0dd--- /dev/null+++ b/e2e/specs/mock/run-files.spec.ts@@ -0,0 +1,355 @@+import { readFile } from 'node:fs/promises';+import { expect, test } from '@playwright/test';+import { FileContext } from 'librechat-data-provider';+import type { TFile, TMessage } from 'librechat-data-provider';+import type { Page } from '@playwright/test';+import type { AgentDetail } from './agents.helpers';+import { cleanupAgent, openAgentBuilder, uniqueAgentName } from './agents.helpers';+import {+ CODE_API_BASE,+ MOCK_ENDPOINTS,+ fetchJson,+ uniqueName,+ messagesView,+ requestJson,+ getAccessToken,+ getRagEmbedded,+ resetProvisioning,+ uploadViaUnifiedButton,+ getCodeProvisionedUploads,+ sendMessageAndWaitForCompletion,+} from './helpers';++function inputPdf(): string {+ const content = 'BT /F1 12 Tf 72 720 Td (Run file sharing input) Tj ET';+ const objects = [+ '<< /Type /Catalog /Pages 2 0 R >>',+ '<< /Type /Pages /Kids [3 0 R] /Count 1 >>',+ '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>',+ `<< /Length ${Buffer.byteLength(content)} >>\nstream\n${content}\nendstream`,+ '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>',+ ];+ let pdf = '%PDF-1.4\n';+ const offsets: number[] = [];+ for (let index = 0; index < objects.length; index++) {+ offsets.push(Buffer.byteLength(pdf));+ pdf += `${index + 1} 0 obj\n${objects[index]}\nendobj\n`;+ }+ const xrefOffset = Buffer.byteLength(pdf);+ pdf += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;+ pdf += offsets.map((offset) => `${String(offset).padStart(10, '0')} 00000 n \n`).join('');+ return `${pdf}trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xrefOffset}\n%%EOF\n`;+}++async function createAgent(+ page: Page,+ token: string,+ name: string,+ fields: Pick<AgentDetail, 'tools' | 'subagents'>,+): Promise<AgentDetail> {+ return requestJson<AgentDetail>(page, {+ path: '/api/agents',+ token,+ method: 'POST',+ body: {+ name,+ description: 'Run-scoped file sharing integration fixture.',+ instructions: 'Follow the test request exactly.',+ provider: MOCK_ENDPOINTS[1].label,+ model: MOCK_ENDPOINTS[1].model,+ ...fields,+ },+ });+}++async function selectAgent(page: Page, name: string): Promise<void> {+ const form = await openAgentBuilder(page);+ await form.getByRole('combobox', { name: 'Agent', exact: true }).click();+ await page.getByRole('option', { name }).click();+ await expect(form.getByLabel('Agent name')).toHaveValue(name);+ await form.getByRole('button', { name: 'Select Agent' }).click();+}++test.describe('run-scoped subagent files', () => {+ test('shares an uploaded PDF lazily and keeps the published CSV usable after reload', async ({+ page,+ }) => {+ test.setTimeout(180_000);+ const label = uniqueName('publication');+ const inputName = `e2e-run-files-${label}.pdf`;+ const outputName = `e2e-run-files-${label}.csv`;+ const parentName = uniqueAgentName('E2E File Parent');+ let childId: string | undefined;+ let parentId: string | undefined;+ const cleanupFiles: TFile[] = [];++ try {+ await page.goto('/c/new');+ const token = await getAccessToken(page);+ const child = await createAgent(page, token, uniqueAgentName('E2E File Child'), {+ tools: ['file_search', 'execute_code'],+ });+ childId = child.id;+ const parent = await createAgent(page, token, parentName, {+ subagents: {+ enabled: true,+ allowSelf: false,+ shareFiles: true,+ agent_ids: [child.id],+ },+ });+ parentId = parent.id;+ await selectAgent(page, parentName);+ await resetProvisioning(page);++ const upload = await uploadViaUnifiedButton(page, {+ name: inputName,+ mimeType: 'application/pdf',+ content: inputPdf(),+ });+ expect(upload.ok()).toBeTruthy();+ const input = (await upload.json()) as TFile;+ cleanupFiles.push(input);+ expect(input.file_id).toBeTruthy();+ expect((await getRagEmbedded(page)).map((file) => file.file_id)).not.toContain(input.file_id);+ expect((await getCodeProvisionedUploads(page)).map((file) => file.filename)).not.toContain(+ inputName,+ );++ const admission = await sendMessageAndWaitForCompletion(+ page,+ `E2E_RUN_FILES:${child.id}:${label}`,+ { timeout: 90_000 },+ );+ const { conversationId } = (await admission.json()) as { conversationId: string };+ await expect(page.getByRole('button', { name: 'Stop generating' })).toBeHidden({+ timeout: 30_000,+ });+ await expect(messagesView(page)).toContainText(`E2E run files complete ${label} file=`);+ await expect+ .poll(async () => (await getRagEmbedded(page)).map((file) => file.file_id))+ .toContain(input.file_id);+ await expect+ .poll(async () => (await getCodeProvisionedUploads(page)).map((file) => file.filename))+ .toContain(inputName);++ const files = await fetchJson<TFile[]>(page, '/api/files', token);+ const published = files.find(+ (file) => file.filename === outputName && file.context === FileContext.run_artifact,+ );+ expect(published, 'publication must create a durable conversation file').toBeDefined();+ if (!published) throw new Error('Published CSV missing from durable files');+ cleanupFiles.push(published);+ expect(published.conversationId).toBe(conversationId);+ expect(published.metadata?.runFile).toMatchObject({+ agentId: child.id,+ inputFileIds: expect.arrayContaining([input.file_id]),+ });+ expect(published.metadata?.runFile?.executionId).toBeTruthy();+ expect(published.metadata?.runFile?.parentExecutionId).toBeTruthy();+ await expect(messagesView(page)).toContainText(+ `E2E run files complete ${label} file=${published.file_id}`,+ );++ const messages = await fetchJson<TMessage[]>(+ page,+ `/api/messages/${encodeURIComponent(conversationId)}`,+ token,+ );+ expect(+ messages.some((message) =>+ message.attachments?.some((attachment) =>+ 'file_id' in attachment ? attachment.file_id === published.file_id : false,+ ),+ ),+ ).toBe(true);++ await page.reload();+ const downloadButton = messagesView(page).getByRole('button', {+ name: `Download ${outputName}`,+ exact: true,+ });+ await expect(downloadButton).toBeVisible({ timeout: 30_000 });+ const downloadPromise = page.waitForEvent('download');+ await downloadButton.click();+ const download = await downloadPromise;+ expect(download.suggestedFilename()).toBe(outputName);+ expect(await download.failure()).toBeNull();++ await page.getByTestId('nav-panel-files').click();+ const filesPanel = page.getByRole('region', { name: 'Files Table' });+ await filesPanel.locator('#filename-filter').fill(outputName);+ const reuse = filesPanel.locator('td[role="button"]').filter({ hasText: outputName });+ await expect(reuse).toHaveCount(1);+ await reuse.press('Enter');+ await expect(+ page.getByTestId('composer-surface').getByRole('button', { name: outputName, exact: true }),+ ).toBeVisible();++ await sendMessageAndWaitForCompletion(+ page,+ `E2E_RUN_FILES_FOLLOWUP:${label}:${published.file_id}`,+ { timeout: 45_000 },+ );+ await expect(messagesView(page)).toContainText(`E2E run file followup ${published.file_id}`);+ } finally {+ if (cleanupFiles.length > 0) {+ await requestJson(page, {+ path: '/api/files',+ token: await getAccessToken(page),+ method: 'DELETE',+ body: { files: cleanupFiles },+ });+ }+ await cleanupAgent(page, parentId);+ await cleanupAgent(page, childId);+ }+ });++ test('retains private versions across inspection and overwrite and downloads both after reload', async ({+ page,+ }) => {+ test.setTimeout(180_000);+ const label = uniqueName('versions');+ const pdfName = `e2e-run-file-versions-${label}.pdf`;+ const csvName = `e2e-run-file-versions-${label}.csv`;+ const outputName = 'analysis.csv';+ const expectedFirst = 'version,total\n1,30\n';+ const expectedSecond = 'version,total\n2,35\n';+ const parentName = uniqueAgentName('E2E Version Parent');+ let childId: string | undefined;+ let parentId: string | undefined;+ const cleanupFiles: TFile[] = [];++ try {+ await page.goto('/c/new');+ const token = await getAccessToken(page);+ const child = await createAgent(page, token, uniqueAgentName('E2E Version Child'), {+ tools: ['file_search', 'execute_code'],+ });+ childId = child.id;+ const parent = await createAgent(page, token, parentName, {+ subagents: {+ enabled: true,+ allowSelf: false,+ shareFiles: true,+ agent_ids: [child.id],+ },+ });+ parentId = parent.id;+ await selectAgent(page, parentName);+ await resetProvisioning(page);++ for (const fixture of [+ { name: pdfName, mimeType: 'application/pdf', content: inputPdf() },+ { name: csvName, mimeType: 'text/csv', content: 'item,amount\nfirst,10\nsecond,20\n' },+ ]) {+ const upload = await uploadViaUnifiedButton(page, fixture);+ expect(upload.ok()).toBeTruthy();+ cleanupFiles.push((await upload.json()) as TFile);+ }+ const inputIds = cleanupFiles.map((file) => file.file_id);+ const admission = await sendMessageAndWaitForCompletion(+ page,+ `E2E_RUN_FILE_VERSIONS:${child.id}:${label}`,+ { timeout: 120_000 },+ );+ const { conversationId } = (await admission.json()) as { conversationId: string };+ await expect(page.getByRole('button', { name: 'Stop generating' })).toBeHidden({+ timeout: 30_000,+ });+ await expect(messagesView(page)).toContainText(`E2E run file versions complete ${label}`);+ const proof = (await messagesView(page).innerText()).match(+ new RegExp(+ `E2E run file versions complete ${label} v1=([\\w.:-]+) v2=([\\w.:-]+) artifact_v1=([\\w.:-]+) artifact_v2=([\\w.:-]+)`,+ ),+ );+ expect(proof, 'parent must confirm both catalog references').not.toBeNull();+ if (!proof) throw new Error('Version publication proof missing');+ const [, firstFileId, secondFileId, firstArtifactId, secondArtifactId] = proof;+ expect(firstFileId).not.toBe(secondFileId);+ expect(firstArtifactId).not.toBe(secondArtifactId);++ const files = await fetchJson<TFile[]>(page, '/api/files', token);+ const published = files.filter(+ (file) =>+ file.conversationId === conversationId && file.context === FileContext.run_artifact,+ );+ cleanupFiles.push(...published);+ expect(published.map((file) => file.file_id).sort()).toEqual(+ [firstFileId, secondFileId].sort(),+ );+ const messages = await fetchJson<TMessage[]>(+ page,+ `/api/messages/${encodeURIComponent(conversationId)}`,+ token,+ );+ for (const file of published) {+ expect(file.filename).toBe(outputName);+ expect(file.metadata?.runFile).toMatchObject({+ agentId: child.id,+ parentAgentId: parent.id,+ inputFileIds: expect.arrayContaining(inputIds),+ });+ expect(file.metadata?.runFile?.executionId).toBeTruthy();+ expect(+ messages.some((message) =>+ message.attachments?.some((attachment) =>+ 'file_id' in attachment ? attachment.file_id === file.file_id : false,+ ),+ ),+ ).toBe(true);+ }+ expect((await getRagEmbedded(page)).map((file) => file.file_id)).toContain(inputIds[0]);+ expect((await getCodeProvisionedUploads(page)).map((file) => file.filename)).toEqual(+ expect.arrayContaining([pdfName, csvName]),+ );+ const overwrittenSource = await page.request.get(+ `${CODE_API_BASE}/v1/download/e2e-run-file-versions-${label}/e2e-versioned-${label}`,+ );+ expect(overwrittenSource.ok()).toBeTruthy();+ expect(await overwrittenSource.text()).toBe(expectedSecond);++ await page.reload();+ const downloadButtons = messagesView(page).getByRole('button', {+ name: `Download ${outputName}`,+ exact: true,+ });+ await expect(downloadButtons).toHaveCount(2, { timeout: 30_000 });+ const expectedIds = new Set([firstFileId, secondFileId]);+ const downloaded = new Map<string, string>();+ for (let index = 0; index < 2; index++) {+ const downloadPromise = page.waitForEvent('download');+ const responsePromise = page.waitForResponse((response) => {+ const pathname = new URL(response.url()).pathname;+ return (+ response.request().method() === 'GET' &&+ pathname.startsWith('/api/files/download/') &&+ expectedIds.has(decodeURIComponent(pathname.split('/').pop() ?? ''))+ );+ });+ await downloadButtons.nth(index).click();+ const [download, response] = await Promise.all([downloadPromise, responsePromise]);+ expect(response.ok()).toBeTruthy();+ expect(download.suggestedFilename()).toBe(outputName);+ expect(await download.failure()).toBeNull();+ const fileId = decodeURIComponent(new URL(response.url()).pathname.split('/').pop() ?? '');+ downloaded.set(fileId, await readFile(await download.path(), 'utf8'));+ }+ expect(downloaded.size).toBe(2);+ expect(downloaded.get(firstFileId)).toBe(expectedFirst);+ expect(downloaded.get(secondFileId)).toBe(expectedSecond);+ } finally {+ if (cleanupFiles.length > 0) {+ await requestJson(page, {+ path: '/api/files',+ token: await getAccessToken(page),+ method: 'DELETE',+ body: { files: cleanupFiles },+ });+ }+ await cleanupAgent(page, parentId);+ await cleanupAgent(page, childId);+ }+ });+});diff --git a/librechat.example.yaml b/librechat.example.yamlindex ac285d70c1..02fad59664 100644--- a/librechat.example.yaml+++ b/librechat.example.yaml@@ -589,6 +589,15 @@ endpoints:# # (optional) Maximum explicit subagents per agent, for both the flat list and# # graph definitions. Defaults to 10; hard cap 50.# maxSubagents: 20+ # # (optional) Shared files during an active agent run. Each delegating agent must+ # # also opt in with subagents.shareFiles. Inputs are read-only; outputs stay+ # # private until explicitly published. Published files remain downloadable.+ # fileSharing:+ # enabled: false+ # allowSiblingSharing: false # permit explicitly named sibling/descendant recipients+ # maxFiles: 100 # manifest capacity, 1–1000+ # maxPrivateBytes: 268435456 # aggregate private output snapshots, 256 MiB+ # ttlMs: 3600000 # active manifest lifetime, at most 24 hours# # (optional) Maximum concurrent Code API uploads per route and user. Defaults to 3.# codeApiUploadConcurrency: 3# # (optional) Maximum total time spent waiting on Code API rate limits. Defaults to 20000 ms.diff --git a/package-lock.json b/package-lock.jsonindex 4331589044..865ea1eaa8 100644--- a/package-lock.json+++ b/package-lock.json@@ -64,7 +64,7 @@"@azure/storage-blob": "^12.30.0","@google/genai": "^2.8.0","@keyv/redis": "5.1.6",- "@librechat/agents": "^3.8.5",+ "@librechat/agents": "^3.8.6","@librechat/api": "*","@librechat/data-schemas": "*","@microsoft/microsoft-graph-client": "^3.0.7",@@ -10610,9 +10610,9 @@}},"node_modules/@librechat/agents": {- "version": "3.8.5",- "resolved": "https://registry.npmjs.org/@librechat/agents/-/agents-3.8.5.tgz",- "integrity": "sha512-Owd8H7lszluwuxN2PyZD/Rtpu6JiTlMhQvViHZ4+Nd0AZB/cLBKNewYgxMlWxcxeigUTm3GBzjIjmV8RFjuq2g==",+ "version": "3.8.6",+ "resolved": "https://registry.npmjs.org/@librechat/agents/-/agents-3.8.6.tgz",+ "integrity": "sha512-9Oar3pfwdJTWm7ppIjRL0SrE38PhHj9r/NsxwMkydVppFGXX1ISWYFGjmvA+XlCdUO/Wv1fVW6wZ6IWlFHfH6g==","license": "MIT","dependencies": {"@anthropic-ai/sdk": "^0.115.0",@@ -42407,7 +42407,7 @@"@azure/storage-blob": "^12.30.0","@google/genai": "^2.8.0","@keyv/redis": "5.1.6",- "@librechat/agents": "^3.8.5",+ "@librechat/agents": "^3.8.6","@librechat/data-schemas": "*","@modelcontextprotocol/sdk": "^1.30.0","@opentelemetry/api": "^1.9.0",diff --git a/packages/api/package.json b/packages/api/package.jsonindex 7306a75a55..647b7076ac 100644--- a/packages/api/package.json+++ b/packages/api/package.json@@ -115,7 +115,7 @@"@azure/storage-blob": "^12.30.0","@google/genai": "^2.8.0","@keyv/redis": "5.1.6",- "@librechat/agents": "^3.8.5",+ "@librechat/agents": "^3.8.6","@librechat/data-schemas": "*","@modelcontextprotocol/sdk": "^1.30.0","@opentelemetry/api": "^1.9.0",diff --git a/packages/api/src/agents/__tests__/initialize.test.ts b/packages/api/src/agents/__tests__/initialize.test.tsindex 1ca43f52aa..67ac3fdebe 100644--- a/packages/api/src/agents/__tests__/initialize.test.ts+++ b/packages/api/src/agents/__tests__/initialize.test.ts@@ -38,10 +38,14 @@ import {ErrorTypes,EModelEndpoint,EToolResources,+ FileContext,+ FileSources,+ AgentCapabilities,+ configSchema,Tools,} from 'librechat-data-provider';import type { IMongoFile } from '@librechat/data-schemas';-import type { Agent } from 'librechat-data-provider';+import type { Agent, TFile } from 'librechat-data-provider';import type { ServerRequest, InitializeResultBase, EndpointTokenConfig } from '~/types';import type { InitializeAgentDbMethods } from '../initialize';import type { CodeExecutionContext } from '../execution';@@ -3689,3 +3693,253 @@ describe('initializeAgent — run-scoped MCP tool definitions', () => {expect(result.accessibleMcpServerNames).toEqual(['db_only_server', rawServerName]);});});++describe('initializeAgent — authorized run file snapshots', () => {+ const resourceMock = jest.requireMock('../resources') as { primeResources: jest.Mock };+ const filterMock = jest.requireMock('~/files') as {+ filterFilesByEndpointRuntimeConfig: jest.Mock;+ };+ const realResources = jest.requireActual<typeof import('../resources')>('../resources');+ const realFilters = jest.requireActual<typeof import('~/files/filter')>('~/files/filter');++ const inputFile = (overrides: Partial<TFile> = {}): TFile => ({+ file_id: 'current-pdf',+ user: 'user-1',+ filename: 'current.pdf',+ filepath: '/uploads/current.pdf',+ type: 'application/pdf',+ source: FileSources.local,+ bytes: 20,+ usage: 1,+ embedded: false,+ object: 'file',+ llmDeliveryPath: 'provider',+ metadata: { destinationChosen: false },+ ...overrides,+ });++ beforeEach(() => {+ jest.clearAllMocks();+ resourceMock.primeResources.mockReset().mockImplementation(realResources.primeResources);+ filterMock.filterFilesByEndpointRuntimeConfig+ .mockReset()+ .mockImplementation(realFilters.filterFilesByEndpointRuntimeConfig);+ });++ afterEach(() => {+ resourceMock.primeResources+ .mockReset()+ .mockResolvedValue({ attachments: [], tool_resources: undefined });+ filterMock.filterFilesByEndpointRuntimeConfig.mockReset().mockReturnValue([]);+ });++ function setup() {+ const result = createMocks();+ result.agent.tools = [Tools.execute_code, Tools.file_search];+ result.agent.endpoint = EModelEndpoint.openAI;+ return result;+ }++ it('reuses current inputs without reading parent history or counting their usage again', async () => {+ const { agent, req, loadTools, db } = setup();+ const file = inputFile();+ const getMessages = jest.fn();+ const getDeferredProvisionFiles = jest.fn();+ const result = await initializeAgent(+ {+ req,+ agent,+ loadTools,+ conversationId: 'parent-conversation',+ parentMessageId: 'previous-parent-message',+ authorizedRunFiles: [file],+ allowedProviders: new Set([Providers.OPENAI]),+ codeEnvAvailable: true,+ fileSearchAvailable: true,+ },+ { ...db, getMessages, getDeferredProvisionFiles },+ );+ expect(result.requestAttachments.map((entry) => entry.file_id)).toEqual([file.file_id]);+ expect(result.provisionState?.codeEnvFiles.map((entry) => entry.file_id)).toEqual([+ file.file_id,+ ]);+ expect(result.provisionState?.vectorDBFiles.map((entry) => entry.file_id)).toEqual([+ file.file_id,+ ]);+ expect(result.requestAttachments[0]).not.toBe(file);+ expect(result.provisionState?.agentScopedFileIds.size).toBe(0);+ expect(getMessages).not.toHaveBeenCalled();+ expect(getDeferredProvisionFiles).not.toHaveBeenCalled();+ expect(db.getConvoFiles).not.toHaveBeenCalled();+ expect(db.getToolFilesByIds).not.toHaveBeenCalled();+ expect(db.getFiles).not.toHaveBeenCalled();+ expect(db.updateFilesUsage).not.toHaveBeenCalled();+ });++ it('still authorizes and primes the child agent own setup files separately', async () => {+ const { agent, req, loadTools, db } = setup();+ const shared = inputFile();+ const setupFile = inputFile({+ file_id: 'child-setup',+ filename: 'setup.txt',+ type: 'text/plain',+ text: 'child setup instructions',+ llmDeliveryPath: 'text',+ context: FileContext.agents,+ });+ if (req.config == null) throw new Error('Missing test configuration');+ req.config.endpoints = { ...req.config.endpoints };+ req.config.endpoints.agents = configSchema.parse({+ version: '1.3.9',+ endpoints: { agents: { capabilities: [AgentCapabilities.context] } },+ }).endpoints?.agents;+ agent.tools?.push(EToolResources.context);+ agent.tool_resources = { context: { file_ids: [setupFile.file_id] } };+ (db.getFiles as jest.Mock).mockResolvedValue([setupFile]);+ const filterFilesByAgentAccess = jest.fn(async ({ files }: { files: TFile[] }) => files);+ const result = await initializeAgent(+ {+ req,+ agent,+ loadTools,+ conversationId: 'parent-conversation',+ authorizedRunFiles: [shared],+ allowedProviders: new Set([Providers.OPENAI]),+ codeEnvAvailable: true,+ fileSearchAvailable: true,+ },+ { ...db, filterFilesByAgentAccess },+ );+ expect(result.requestAttachments.map((entry) => entry.file_id)).toEqual([shared.file_id]);+ expect(result.agentContextAttachments.map((entry) => entry.file_id)).toEqual([+ setupFile.file_id,+ ]);+ expect(result.provisionState?.agentScopedFileIds).toEqual(new Set([setupFile.file_id]));+ expect(filterFilesByAgentAccess).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: agent.id, userId: 'user-1', files: [setupFile] }),+ );+ expect(db.getFiles).toHaveBeenCalledTimes(1);+ expect(db.getConvoFiles).not.toHaveBeenCalled();+ });++ it('treats an empty authorized snapshot as no shared inputs', async () => {+ const { agent, req, loadTools, db } = setup();+ (db.getConvoFiles as jest.Mock).mockResolvedValue(['unrelated-history']);+ const result = await initializeAgent(+ {+ req,+ agent,+ loadTools,+ conversationId: 'parent-conversation',+ authorizedRunFiles: [],+ allowedProviders: new Set([Providers.OPENAI]),+ codeEnvAvailable: true,+ },+ db,+ );+ expect(result.requestAttachments).toEqual([]);+ expect(result.provisionState).toBeUndefined();+ expect(db.getConvoFiles).not.toHaveBeenCalled();+ });++ it.each([{ user: 'foreign-user' }, { tenantId: 'foreign-tenant' }])(+ 'rejects an incorrectly scoped snapshot before priming: %o',+ async (difference) => {+ const { agent, req, loadTools, db } = setup();+ await expect(+ initializeAgent(+ {+ req,+ agent,+ loadTools,+ authorizedRunFiles: [inputFile(difference)],+ allowedProviders: new Set([Providers.OPENAI]),+ codeEnvAvailable: true,+ },+ db,+ ),+ ).rejects.toThrow('authenticated owner');+ expect(resourceMock.primeResources).not.toHaveBeenCalled();+ },+ );++ it('applies the child endpoint policy to the supplied snapshot', async () => {+ const { agent, req, loadTools, db } = setup();+ if (req.config == null) throw new Error('Missing test configuration');+ req.config.fileConfig = { endpoints: { [EModelEndpoint.openAI]: { disabled: true } } };+ const result = await initializeAgent(+ {+ req,+ agent,+ loadTools,+ authorizedRunFiles: [inputFile()],+ allowedProviders: new Set([Providers.OPENAI]),+ codeEnvAvailable: true,+ },+ db,+ );+ expect(result.requestAttachments).toEqual([]);+ expect(result.provisionState).toBeUndefined();+ });++ it('checks current content policy before a shared text file reaches a child', async () => {+ const { agent, req, loadTools, db } = setup();+ if (req.config == null) throw new Error('Missing test configuration');+ req.config.filters = {+ files: {+ pii: {+ starterPatterns: [],+ customPatterns: [{ id: 'private', label: 'private value', regex: 'PRIVATE-[A-Z]+' }],+ },+ },+ };+ await expect(+ initializeAgent(+ {+ req,+ agent,+ loadTools,+ authorizedRunFiles: [inputFile({ llmDeliveryPath: 'text', text: 'PRIVATE-SECRET' })],+ allowedProviders: new Set([Providers.OPENAI]),+ codeEnvAvailable: true,+ },+ db,+ ),+ ).rejects.toMatchObject({ code: 'content_filter_block' });+ expect(resourceMock.primeResources).not.toHaveBeenCalled();+ });++ it('returns only exact current request IDs for seeding a shared-file manifest', async () => {+ const { agent, req, loadTools, db } = setup();+ const current = inputFile();+ const historical = inputFile({ file_id: 'history-file', embedded: true });+ mockExtractLibreChatParams.mockReturnValueOnce({+ resendFiles: true,+ modelOptions: { model: agent.model },+ });+ (db.getFiles as jest.Mock).mockResolvedValue([current, historical]);+ (db.getConvoFiles as jest.Mock).mockResolvedValue([historical.file_id]);+ (db.getToolFilesByIds as jest.Mock).mockResolvedValue([historical]);+ const result = await initializeAgent(+ {+ req,+ agent,+ loadTools,+ conversationId: 'parent-conversation',+ requestFiles: [{ file_id: current.file_id } as IMongoFile],+ allowedProviders: new Set([Providers.OPENAI]),+ codeEnvAvailable: true,+ fileSearchAvailable: true,+ },+ db,+ );+ expect(result.requestAttachments.map((entry) => entry.file_id)).toEqual([+ current.file_id,+ historical.file_id,+ ]);+ expect(result.currentRequestAttachments.map((entry) => entry.file_id)).toEqual([+ current.file_id,+ ]);+ expect(result.currentRequestAttachments[0].user).toBe('user-1');+ });+});diff --git a/packages/api/src/agents/files/binding.ts b/packages/api/src/agents/files/binding.tsnew file mode 100644index 0000000000..239be439a4--- /dev/null+++ b/packages/api/src/agents/files/binding.ts@@ -0,0 +1,187 @@+import { agentsEndpointSchema } from 'librechat-data-provider';+import type { CodeEnvFile, SubagentExecutionContext } from '@librechat/agents';+import type { TFile } from 'librechat-data-provider';+import type { PublishedCodeOutputResult } from '~/files/code/publication';+import type { ServerRequest, StrategyFunctions } from '~/types';+import type { CodeExecutionContext } from '~/agents/execution';+import type { RunFileMessageEncoderDeps } from './encode';+import type { ToolEndCallback } from '~/agents/handlers';+import type { RunFileHost } from './host';+import { createRunArtifactSnapshotAdapter } from '~/files/code/snapshot';+import { createRunArtifactPublisher } from '~/files/code/publication';+import { createRunFileSnapshotStore } from './snapshots';+import { createRunFileMessageEncoder } from './encode';+import { createRunFileHost } from './host';++type HostOptions = Parameters<typeof createRunFileHost>[0];+type PublisherOptions = Parameters<typeof createRunArtifactPublisher>[0];++type ProvisionCallback = (+ names: string[],+ agentId?: string,+ signal?: AbortSignal,+) => Promise<CodeEnvFile[] | void>;++export interface ChatRunFileBindings extends RunFileHost {+ getCodeExecutionContext: (+ agentId: string,+ context?: SubagentExecutionContext,+ ) => CodeExecutionContext | undefined;+ wrapProvision: (+ fallback: ProvisionCallback,+ ) => (+ names: string[],+ agentId?: string,+ signal?: AbortSignal,+ context?: SubagentExecutionContext,+ ) => Promise<CodeEnvFile[] | void>;+ wrapToolEnd: (fallback: ToolEndCallback) => ToolEndCallback;+}++/** Binds the existing storage, preview, and SSE adapters without giving shared files another pipeline. */+export function createChatRunFileBindings({+ req,+ contexts,+ createdAt = Date.now(),+ audit,+ requestFiles,+ getInputs,+ loadFiles,+ filterFiles,+ listPublications,+ provisioning,+ fileMethods,+ processCodeOutput,+ snapshotAdapter,+ finalize,+ encoder,+ getStrategyFunctions,+ artifactPromises,+ emitAttachment,+}: {+ req: ServerRequest;+ contexts: HostOptions['contexts'];+ createdAt?: number;+ audit?: HostOptions['audit'];+ requestFiles: readonly { file_id?: string }[];+ getInputs: HostOptions['getInputs'];+ loadFiles: HostOptions['loadFiles'];+ filterFiles: HostOptions['filterFiles'];+ listPublications: HostOptions['listPublications'];+ provisioning: HostOptions['provisioning'];+ fileMethods: Pick<+ PublisherOptions,+ 'claimRunArtifactFile' | 'publishRunArtifactFile' | 'findRunArtifactFile'+ >;+ processCodeOutput: (+ input: Parameters<PublisherOptions['processCodeOutput']>[0] & { req: ServerRequest },+ ) => ReturnType<PublisherOptions['processCodeOutput']>;+ snapshotAdapter: Omit<Parameters<typeof createRunArtifactSnapshotAdapter>[0], 'req'>;+ finalize: (input: {+ finalize?: PublishedCodeOutputResult['finalize'];+ fileId?: string;+ previewRevision?: string;+ }) => void;+ encoder: Omit<RunFileMessageEncoderDeps, 'req' | 'getStrategyFunctions'>;+ getStrategyFunctions: (source: string) => StrategyFunctions;+ artifactPromises: Array<Promise<TFile | null>>;+ emitAttachment: (file: TFile) => void;+}): ChatRunFileBindings {+ const policy =+ req.config?.endpoints?.agents?.fileSharing ??+ agentsEndpointSchema.parse({ fileSharing: {} }).fileSharing!;+ const adapter = createRunArtifactSnapshotAdapter({ ...snapshotAdapter, req });+ const snapshots = createRunFileSnapshotStore({+ open: adapter.open,+ maxBytes: policy.maxPrivateBytes,+ // One temporary comparison slot lets unchanged read results deduplicate even+ // at catalog capacity. The manifest still enforces the configured file count.+ maxFiles: policy.maxFiles + 1,+ });+ const publishArtifact = createRunArtifactPublisher({+ ...fileMethods,+ processCodeOutput: (input) => processCodeOutput({ ...input, req }),+ prepare: async (artifact, signal) => {+ if (!artifact.snapshotId)+ throw new Error(+ 'The private output snapshot is unavailable. Regenerate the file before publishing.',+ );+ const buffer = await snapshots.read(artifact.snapshotId, signal);+ return adapter.prepare(artifact, buffer, signal);+ },+ discard: async (file) => {+ const strategy = getStrategyFunctions(file.source ?? 'local');+ if (!strategy.deleteFile) throw new Error('The artifact storage does not support cleanup.');+ await strategy.deleteFile(req, file);+ },+ finalize: (result) =>+ finalize({+ finalize: result.finalize,+ fileId: result.file?.file_id,+ previewRevision: result.previewRevision,+ }),+ });+ const emitted = new Set<string>();+ const messageEncoder = createRunFileMessageEncoder({ ...encoder, req, getStrategyFunctions });+ const host = createRunFileHost({+ req,+ contexts,+ createdAt,+ audit,+ getInputs,+ loadFiles,+ filterFiles,+ listPublications,+ snapshots,+ provisioning,+ inputFileIds: new Set(requestFiles.flatMap((file) => (file.file_id ? [file.file_id] : []))),+ validateMessages: messageEncoder.validate,+ encodeMessages: messageEncoder.encode,+ publish: async ({ scope, artifact, provenance, signal }) => {+ signal?.throwIfAborted();+ const file = await publishArtifact({+ scope: {+ ...scope,+ executionId: provenance.executionId,+ agentId: provenance.agentId,+ sourceFileId: provenance.sourceFileId,+ },+ artifact,+ provenance,+ signal,+ });+ signal?.throwIfAborted();+ return file;+ },+ emit: async (file) => {+ if (!emitted.has(file.file_id)) {+ artifactPromises.push(Promise.resolve(file));+ emitted.add(file.file_id);+ }+ emitAttachment(file);+ },+ });++ return {+ ...host,+ getCodeExecutionContext: (agentId: string, context?: Parameters<typeof host.getContext>[1]) =>+ host.session.isActive() ? host.getContext(agentId, context)?.codeExecutionContext : undefined,+ wrapProvision:+ (fallback: ProvisionCallback) =>+ async (+ names: string[],+ agentId?: string,+ signal?: AbortSignal,+ context?: Parameters<typeof host.getContext>[1],+ ) => {+ if (!host.session.isActive()) return fallback(names, agentId, signal);+ if (!agentId || !signal)+ throw new Error('Shared-file provisioning requires an execution identity.');+ return host.provisionPrepared(names, agentId, signal, context);+ },+ wrapToolEnd:+ (fallback: ToolEndCallback): ToolEndCallback =>+ (data, metadata) =>+ host.deliverToolEnd(fallback, data, metadata),+ };+}diff --git a/packages/api/src/agents/files/encode.spec.ts b/packages/api/src/agents/files/encode.spec.tsnew file mode 100644index 0000000000..753db6d098--- /dev/null+++ b/packages/api/src/agents/files/encode.spec.ts@@ -0,0 +1,404 @@+import { FileSources, ImageDetail } from 'librechat-data-provider';+import type { TFile } from 'librechat-data-provider';+import type { RunFileEncodingAgent, RunFileMessageEncoderDeps } from './encode';+import type { ServerRequest } from '~/types';+import { AgentAttachmentLimitError, AgentAttachmentPolicyError } from '../attachments';+import { createRunFileMessageEncoder } from './encode';++jest.mock('~/utils/tokenizer', () => ({ countTokens: (text: string) => text.length }));+import { extractFileContext } from '~/files/context';++const pdf: TFile = {+ file_id: 'input-pdf',+ filename: 'report.pdf',+ type: 'application/pdf',+ bytes: 20,+ user: 'user',+ embedded: false,+ filepath: '/files/report.pdf',+ object: 'file',+ usage: 0,+ source: FileSources.local,+ llmDeliveryPath: 'provider',+ text: 'Previously extracted text',+};+const nativeDocument = {+ type: 'file',+ file: { filename: 'report.pdf', file_data: 'data:application/pdf;base64,cGRm' },+};+const nativeImage = { type: 'image_url', image_url: { url: 'data:image/png;base64,aW1n' } };++function setup({+ fileConfig = {},+ agents = { child: { provider: 'openAI' } },+}: {+ fileConfig?: NonNullable<ServerRequest['config']>['fileConfig'];+ agents?: Record<string, RunFileEncodingAgent>;+} = {}) {+ const req = { body: {}, config: { fileConfig } } as ServerRequest;+ const encodeImages = jest.fn(async () => ({ image_urls: [nativeImage] }));+ const encodeDocuments = jest.fn(async () => ({ documents: [nativeDocument] }));+ const encodeAudios = jest.fn(async () => ({ audios: [{ type: 'media', data: 'audio' }] }));+ const encodeVideos = jest.fn(async () => ({ videos: [{ type: 'media', data: 'video' }] }));+ const extractText = jest.fn<+ ReturnType<RunFileMessageEncoderDeps['extractText']>,+ Parameters<RunFileMessageEncoderDeps['extractText']>+ >(extractFileContext);+ const deps: RunFileMessageEncoderDeps = {+ req,+ getAgent: (id) => agents[id],+ encodeImages,+ encodeDocuments,+ encodeAudios,+ encodeVideos,+ getStrategyFunctions: jest.fn(),+ extractText,+ };+ return { ...deps, ...createRunFileMessageEncoder(deps) };+}++describe('createRunFileMessageEncoder', () => {+ it('sends PDF and image provider blocks to the child without duplicating extracted text', async () => {+ const harness = setup({+ agents: {+ child: {+ provider: 'openAI',+ endpoint: 'child-provider',+ model: 'child-model',+ model_parameters: { useResponsesApi: true },+ imageDetail: ImageDetail.high,+ },+ },+ });+ const image: TFile = {+ ...pdf,+ file_id: 'image',+ filename: 'figure.png',+ type: 'image/png',+ embedded: true,+ metadata: { fileIdentifier: 'already-provisioned' },+ };++ const messages = await harness.encode([pdf, image], 'child');++ expect(messages).toHaveLength(1);+ expect(messages[0]._getType()).toBe('human');+ expect(messages[0].content).toEqual(expect.arrayContaining([nativeDocument, nativeImage]));+ expect(JSON.stringify(messages[0].content)).not.toContain(pdf.text);+ expect(harness.extractText).not.toHaveBeenCalled();+ expect(harness.encodeDocuments).toHaveBeenCalledWith(+ harness.req,+ [pdf],+ expect.objectContaining({+ provider: 'openAI',+ endpoint: 'child-provider',+ model: 'child-model',+ useResponsesApi: true,+ imageDetail: 'high',+ }),+ harness.getStrategyFunctions,+ );+ expect(harness.encodeImages).toHaveBeenCalledWith(+ harness.req,+ [image],+ expect.any(Object),+ harness.getStrategyFunctions,+ );+ });++ it('resolves one inferred input independently for provider, text and tool-only children', async () => {+ const harness = setup({+ agents: {+ native: { provider: 'openAI', endpoint: 'native' },+ text: { provider: 'openAI', endpoint: 'text' },+ tools: { provider: 'openAI', endpoint: 'tools' },+ },+ fileConfig: {+ endpoints: {+ native: { defaultLLMDeliveryPath: { fallback: 'provider' } },+ text: { defaultLLMDeliveryPath: { fallback: 'text' } },+ tools: { defaultLLMDeliveryPath: { fallback: 'none' } },+ },+ },+ });+ const [native, text, tools] = await Promise.all([+ harness.encode([pdf], 'native'),+ harness.encode([pdf], 'text'),+ harness.encode([pdf], 'tools'),+ ]);++ expect(native[0].content).toEqual(expect.arrayContaining([nativeDocument]));+ expect(JSON.stringify(text[0].content)).toContain(pdf.text);+ expect(JSON.stringify(text[0].content)).not.toContain('data:application/pdf');+ expect(tools).toEqual([]);+ expect(harness.encodeDocuments).toHaveBeenCalledTimes(1);+ expect(harness.extractText).toHaveBeenCalledWith(+ expect.objectContaining({ attachments: [{ ...pdf, llmDeliveryPath: 'text' }] }),+ );+ expect(pdf.llmDeliveryPath).toBe('provider');+ });++ it('honors an explicit tool destination even when the receiving endpoint supports native files', async () => {+ const harness = setup();+ const file: TFile = {+ ...pdf,+ source: FileSources.text,+ llmDeliveryPath: 'none',+ metadata: { destinationChosen: true },+ };+ await expect(harness.encode([file], 'child')).resolves.toEqual([]);+ expect(harness.encodeDocuments).not.toHaveBeenCalled();+ expect(harness.extractText).not.toHaveBeenCalled();+ });++ it.each([+ {+ route: 'explicit tool destination',+ file: { llmDeliveryPath: 'none', metadata: { destinationChosen: true } },+ },+ {+ route: 'explicit tool destination on a text source',+ file: {+ source: FileSources.text,+ llmDeliveryPath: 'none',+ metadata: { destinationChosen: true },+ },+ },+ { route: 'inferred tool destination', file: { llmDeliveryPath: 'provider' } },+ ] satisfies { route: string; file: Partial<TFile> }[])(+ 'excludes $route files from model count, bytes and text budgets',+ async ({ file }) => {+ const harness = setup({+ fileConfig: {+ fileContextSizeLimit: 1,+ fileContextCharLimit: 5,+ endpoints: {+ openAI: { fileLimit: 1, defaultLLMDeliveryPath: { fallback: 'none' } },+ },+ },+ });+ const input: TFile = { ...pdf, ...file, bytes: 2 * 1024 * 1024 };++ await expect(+ harness.encode([input, { ...input, file_id: 'second' }], 'child'),+ ).resolves.toEqual([]);+ expect(harness.encodeDocuments).not.toHaveBeenCalled();+ expect(harness.extractText).not.toHaveBeenCalled();+ },+ );++ it.each(['provider', 'text'] as const)(+ 'counts an inferred tool-only input when the child resolves it to %s delivery',+ async (fallback) => {+ const harness = setup({+ fileConfig: {+ fileContextSizeLimit: 1,+ endpoints: { openAI: { defaultLLMDeliveryPath: { fallback } } },+ },+ });+ await expect(+ harness.encode([{ ...pdf, llmDeliveryPath: 'none', bytes: 2 * 1024 * 1024 }], 'child'),+ ).rejects.toMatchObject({ limitType: 'bytes' });+ expect(harness.encodeDocuments).not.toHaveBeenCalled();+ expect(harness.extractText).not.toHaveBeenCalled();+ },+ );++ it('rejects a child text route without extracted text before reading any files', async () => {+ const harness = setup({+ fileConfig: {+ endpoints: { openAI: { defaultLLMDeliveryPath: { fallback: 'text' } } },+ },+ });+ await expect(harness.encode([{ ...pdf, text: undefined }], 'child')).rejects.toThrow(+ 'requires extracted text for this agent',+ );+ expect(harness.encodeDocuments).not.toHaveBeenCalled();+ expect(harness.extractText).not.toHaveBeenCalled();+ });++ it('keeps legacy extracted text while excluding legacy tool-provisioned native bytes', async () => {+ const harness = setup({+ fileConfig: {+ fileContextSizeLimit: 1,+ endpoints: { openAI: { fileLimit: 1 } },+ },+ });+ const files: TFile[] = [+ { ...pdf, file_id: 'legacy-text', source: FileSources.text, llmDeliveryPath: undefined },+ {+ ...pdf,+ file_id: 'legacy-tool',+ embedded: true,+ llmDeliveryPath: undefined,+ bytes: 2 * 1024 * 1024,+ },+ ];+ const messages = await harness.encode(files, 'child');+ expect(JSON.stringify(messages[0].content)).toContain(pdf.text);+ expect(harness.encodeDocuments).not.toHaveBeenCalled();+ });++ it('uses the upload MIME type for policy after image conversion', async () => {+ const harness = setup({+ fileConfig: { endpoints: { openAI: { supportedMimeTypes: ['image/heic'] } } },+ });+ const image: TFile = {+ ...pdf,+ type: 'image/webp',+ metadata: { routingMimeType: 'image/heic' },+ };+ const messages = await harness.encode([image], 'child');+ expect(messages[0].content).toEqual(expect.arrayContaining([nativeImage]));+ });++ it('passes audio and video to the receiving provider encoders', async () => {+ const harness = setup({ agents: { child: { provider: 'google' } } });+ await harness.encode(+ [+ { ...pdf, file_id: 'audio', type: 'audio/mpeg' },+ { ...pdf, file_id: 'video', type: 'video/mp4' },+ ],+ 'child',+ );+ expect(harness.encodeAudios).toHaveBeenCalledTimes(1);+ expect(harness.encodeVideos).toHaveBeenCalledTimes(1);+ expect(harness.encodeDocuments).not.toHaveBeenCalled();+ });++ it.each([{ disabled: true }, { supportedMimeTypes: ['image/png'] }, { fileSizeLimit: 0.000001 }])(+ 'rejects incompatible child policy before reading bytes: %j',+ async (policy) => {+ const harness = setup({ fileConfig: { endpoints: { openAI: policy } } });+ await expect(harness.encode([pdf], 'child')).rejects.toBeInstanceOf(+ AgentAttachmentPolicyError,+ );+ await expect(+ harness.encode(+ [{ ...pdf, llmDeliveryPath: 'none', metadata: { destinationChosen: true } }],+ 'child',+ ),+ ).rejects.toBeInstanceOf(AgentAttachmentPolicyError);+ expect(harness.encodeDocuments).not.toHaveBeenCalled();+ expect(harness.extractText).not.toHaveBeenCalled();+ },+ );++ it('includes permanent child context in the count budget before encoding shared files', async () => {+ const harness = setup({+ agents: {+ child: {+ provider: 'openAI',+ agentContextAttachments: [{ ...pdf, file_id: 'permanent' }],+ },+ },+ fileConfig: { endpoints: { openAI: { fileLimit: 1 } } },+ });+ await expect(harness.encode([pdf], 'child')).rejects.toMatchObject({ limitType: 'count' });+ expect(harness.encodeDocuments).not.toHaveBeenCalled();+ });++ it('budgets mixed inputs with permanent model context once and excludes permanent tool files', async () => {+ const permanent: TFile = { ...pdf, file_id: 'permanent' };+ const tool: TFile = {+ ...pdf,+ file_id: 'tool',+ llmDeliveryPath: 'none',+ metadata: { destinationChosen: true },+ bytes: 2 * 1024 * 1024,+ };+ const harness = setup({+ agents: {+ child: {+ provider: 'openAI',+ agentContextAttachments: [permanent, { ...tool, file_id: 'permanent-tool' }],+ },+ },+ fileConfig: {+ fileContextSizeLimit: 1,+ endpoints: { openAI: { fileLimit: 2 } },+ },+ });++ const messages = await harness.encode([permanent, pdf, tool], 'child');++ expect(messages).toHaveLength(1);+ expect(messages[0].content).toEqual(expect.arrayContaining([nativeDocument]));+ expect(harness.encodeDocuments).toHaveBeenCalledWith(+ harness.req,+ [permanent, pdf],+ expect.any(Object),+ harness.getStrategyFunctions,+ );+ expect(harness.extractText).not.toHaveBeenCalled();+ });++ it('rejects aggregate file bytes before encoding', async () => {+ const harness = setup({ fileConfig: { endpoints: { openAI: { totalSizeLimit: 1 } } } });+ await expect(+ harness.encode(+ [+ { ...pdf, bytes: 600_000 },+ { ...pdf, file_id: 'second', bytes: 600_000 },+ ],+ 'child',+ ),+ ).rejects.toMatchObject({ limitType: 'bytes' });+ expect(harness.encodeDocuments).not.toHaveBeenCalled();+ });++ it('enforces the extracted-text budget before formatting the child prompt', async () => {+ const harness = setup({ fileConfig: { fileContextCharLimit: 5 } });+ await expect(+ harness.encode(+ [{ ...pdf, llmDeliveryPath: 'text', metadata: { destinationChosen: true } }],+ 'child',+ ),+ ).rejects.toBeInstanceOf(AgentAttachmentLimitError);+ expect(harness.extractText).not.toHaveBeenCalled();+ });++ it('propagates encoder failures rather than silently dropping a shared input', async () => {+ const harness = setup();+ const failure = new Error('The input is no longer in storage');+ jest.mocked(harness.encodeDocuments).mockRejectedValueOnce(failure);+ await expect(harness.encode([pdf], 'child')).rejects.toBe(failure);+ });++ it.each(['provider', 'none'] as const)(+ 'screens %s file content with the deployment policy before encoding',+ async (llmDeliveryPath) => {+ const harness = setup();+ harness.req.config!.filters = {+ files: {+ pii: {+ fields: ['name'],+ starterPatterns: [],+ customPatterns: [{ id: 'private', label: 'private value', regex: 'PRIVATE-[A-Z]+' }],+ },+ },+ };+ await expect(+ harness.encode(+ [+ {+ ...pdf,+ filename: 'PRIVATE-DOC.pdf',+ llmDeliveryPath,+ metadata: { destinationChosen: true },+ },+ ],+ 'child',+ ),+ ).rejects.toThrow('Submitted content contains a private value');+ expect(harness.encodeDocuments).not.toHaveBeenCalled();+ },+ );++ it('returns no extra message or storage access when no files are shared', async () => {+ const harness = setup();+ await expect(harness.encode([], 'child')).resolves.toEqual([]);+ expect(harness.encodeDocuments).not.toHaveBeenCalled();+ expect(harness.extractText).not.toHaveBeenCalled();+ });+});diff --git a/packages/api/src/agents/files/encode.ts b/packages/api/src/agents/files/encode.tsnew file mode 100644index 0000000000..63b273bd76--- /dev/null+++ b/packages/api/src/agents/files/encode.ts@@ -0,0 +1,231 @@+import { formatMessage } from '@librechat/agents';+import { HumanMessage } from '@librechat/agents/langchain';+import {+ FileSources,+ EModelEndpoint,+ mergeFileConfig,+ getEndpointFileConfig,+ isBedrockDocumentType,+ resolveUseResponsesApi,+ isSpeechProviderConfigured,+ resolveUploadLLMDeliveryPath,+} from 'librechat-data-provider';+import type { TFile, ImageDetail } from 'librechat-data-provider';+import type { BaseMessage } from '@librechat/agents/langchain';+import type { ServerRequest, StrategyFunctions } from '~/types';+import type { TokenCountFn } from '~/utils/text';+import {+ isModelBoundAttachmentFile,+ assertAgentAttachmentLimits,+ AgentAttachmentPolicyError,+} from '../attachments';+import { assertModelBoundContent } from '~/middleware/modelBoundContent';+import { filterFilesByEndpointRuntimeConfig } from '~/files/filter';+import { countTokens } from '~/utils/tokenizer';++type ContentBlock = Exclude<BaseMessage['content'], string>[number];++/** The already loaded child configuration; storage documents never cross this boundary. */+export interface RunFileEncodingAgent {+ provider: string;+ endpoint?: string | null;+ model?: string | null;+ model_parameters?: { model?: string; useResponsesApi?: boolean };+ imageDetail?: ImageDetail;+ agentContextAttachments?: readonly TFile[];+}++export interface RunFileEncodingParams {+ provider: string;+ endpoint: string;+ model?: string;+ useResponsesApi?: boolean;+ imageDetail?: ImageDetail;+}++type MediaEncoder<T> = (+ req: ServerRequest,+ files: TFile[],+ params: RunFileEncodingParams,+ getStrategyFunctions: (source: string) => StrategyFunctions,+) => Promise<T>;++/** Adapters bind the existing attachment encoders to the host's storage strategies. */+export interface RunFileMessageEncoderDeps {+ req: ServerRequest;+ getAgent: (agentId: string) => RunFileEncodingAgent | undefined;+ encodeImages: MediaEncoder<{ image_urls: ContentBlock[] }>;+ encodeDocuments: MediaEncoder<{ documents: ContentBlock[] }>;+ encodeAudios: MediaEncoder<{ audios: ContentBlock[] }>;+ encodeVideos: MediaEncoder<{ videos: ContentBlock[] }>;+ getStrategyFunctions: (source: string) => StrategyFunctions;+ extractText: (params: {+ attachments: TFile[];+ req: ServerRequest;+ tokenCountFn: TokenCountFn;+ }) => Promise<string | undefined>;+}++export interface RunFileMessageEncoder {+ validate: (files: TFile[], agentId: string) => void;+ encode: (files: TFile[], agentId: string) => Promise<BaseMessage[]>;+}++/** Encodes authorized run files for the receiving child, without provisioning new resources. */+export function createRunFileMessageEncoder(+ deps: RunFileMessageEncoderDeps,+): RunFileMessageEncoder {+ function prepare(files: TFile[], agentId: string) {+ const agent = deps.getAgent(agentId);+ if (!agent) {+ throw new Error('The target agent is not available for shared file delivery.');+ }+ const endpoint = agent.endpoint ?? agent.provider;+ const fileConfig = mergeFileConfig(deps.req.config?.fileConfig);+ const endpointConfig = getEndpointFileConfig({ fileConfig, endpoint });+ const useResponsesApi = resolveUseResponsesApi(agent.model_parameters?.useResponsesApi);+ const params: RunFileEncodingParams = {+ provider: agent.provider,+ endpoint,+ model: agent.model_parameters?.model ?? agent.model ?? undefined,+ useResponsesApi,+ imageDetail: agent.imageDetail,+ };++ const resolveDelivery = (file: TFile): TFile => {+ if (file.llmDeliveryPath == null || file.metadata?.destinationChosen === true) {+ return file;+ }+ return {+ ...file,+ llmDeliveryPath: resolveUploadLLMDeliveryPath({+ mimeType: file.metadata?.routingMimeType ?? file.type,+ endpointConfig,+ fileConfig,+ endpoint,+ useResponsesApi,+ sttConfigured: isSpeechProviderConfigured(deps.req.config?.speech?.stt),+ }),+ };+ };+ const sharedFiles = files.map(resolveDelivery);+ const compatibleFiles = filterFilesByEndpointRuntimeConfig(deps.req.config, {+ files: sharedFiles,+ endpoint,+ skipTotalSizeLimit: true,+ preserveTextSources: true,+ });+ if (compatibleFiles.length !== sharedFiles.length) {+ throw new AgentAttachmentPolicyError();+ }+ const budgetFiles = new Map(+ [...(agent.agentContextAttachments ?? []).map(resolveDelivery), ...sharedFiles].map(+ (file) => [file.file_id, file] as const,+ ),+ );+ assertAgentAttachmentLimits({+ attachments: [...budgetFiles.values()].filter(+ (file) => file.llmDeliveryPath !== 'none' && isModelBoundAttachmentFile(file),+ ),+ req: deps.req,+ endpoint,+ });+ assertModelBoundContent({ filters: deps.req.config?.filters, files: sharedFiles });+ return { agent, params, sharedFiles, fileConfig, endpointConfig };+ }++ function validate(files: TFile[], agentId: string): void {+ if (files.length > 0) prepare(files, agentId);+ }++ async function encode(files: TFile[], agentId: string): Promise<BaseMessage[]> {+ if (files.length === 0) return [];+ const { agent, params, sharedFiles, fileConfig, endpointConfig } = prepare(files, agentId);+ const images: TFile[] = [];+ const documents: TFile[] = [];+ const audios: TFile[] = [];+ const videos: TFile[] = [];+ const textFiles: TFile[] = [];+ for (const file of sharedFiles) {+ const deliveryPath = file.llmDeliveryPath;+ if (deliveryPath === 'none') {+ continue;+ }+ if (deliveryPath === 'text' && !file.text) {+ throw new Error(+ `Shared file "${file.filename}" requires extracted text for this agent. Attach a text version or use an agent that supports the original file.`,+ );+ }+ if (deliveryPath == null || deliveryPath === 'text') {+ textFiles.push(file);+ }+ if ((file.source ?? FileSources.local) === FileSources.text || deliveryPath === 'text') {+ continue;+ }+ /* Provisioning may add tool references to native files. Only legacy records use+ * those references to decide whether their bytes belong in the prompt. */+ if (+ deliveryPath !== 'provider' &&+ (file.embedded === true ||+ file.metadata?.codeEnvRef != null ||+ file.metadata?.codeEnvRefs != null ||+ file.metadata?.fileIdentifier != null)+ ) {+ continue;+ }+ if (file.type.startsWith('image/')) {+ images.push(file);+ } else if (+ file.type === 'application/pdf' ||+ (agent.provider === EModelEndpoint.bedrock && isBedrockDocumentType(file.type))+ ) {+ documents.push(file);+ } else if (file.type.startsWith('audio/')) {+ audios.push(file);+ } else if (file.type.startsWith('video/')) {+ videos.push(file);+ } else if (+ endpointConfig.supportedMimeTypes &&+ fileConfig.checkType?.(file.type, endpointConfig.supportedMimeTypes)+ ) {+ documents.push(file);+ }+ }++ const encodeMedia = <T>(encoder: MediaEncoder<T>, inputs: TFile[], empty: T): Promise<T> =>+ inputs.length > 0+ ? encoder(deps.req, inputs, params, deps.getStrategyFunctions)+ : Promise.resolve(empty);+ const [imageResult, documentResult, audioResult, videoResult, text] = await Promise.all([+ encodeMedia(deps.encodeImages, images, { image_urls: [] }),+ encodeMedia(deps.encodeDocuments, documents, { documents: [] }),+ encodeMedia(deps.encodeAudios, audios, { audios: [] }),+ encodeMedia(deps.encodeVideos, videos, { videos: [] }),+ textFiles.length > 0+ ? deps.extractText({ attachments: textFiles, req: deps.req, tokenCountFn: countTokens })+ : Promise.resolve(undefined),+ ]);+ if (+ !text &&+ imageResult.image_urls.length === 0 &&+ documentResult.documents.length === 0 &&+ audioResult.audios.length === 0 &&+ videoResult.videos.length === 0+ ) {+ return [];+ }+ const formatted = formatMessage({+ message: {+ role: 'user',+ content: text ?? 'Read-only files shared for this task.',+ image_urls: imageResult.image_urls,+ documents: documentResult.documents,+ audios: audioResult.audios,+ videos: videoResult.videos,+ } as Parameters<typeof formatMessage>[0]['message'],+ });+ return [new HumanMessage({ content: formatted.content as BaseMessage['content'] })];+ }++ return { validate, encode };+}diff --git a/packages/api/src/agents/files/handlers.spec.ts b/packages/api/src/agents/files/handlers.spec.tsnew file mode 100644index 0000000000..4abecea911--- /dev/null+++ b/packages/api/src/agents/files/handlers.spec.ts@@ -0,0 +1,306 @@+jest.mock('../prewarm', () => ({ markSandboxReady: jest.fn() }));++import { z } from 'zod';+import { ToolMessage } from '@librechat/agents/langchain';+import { tool } from '@librechat/agents/langchain/tools';+import type {+ SubagentExecutionContext,+ ToolExecuteBatchRequest,+ ToolExecuteResult,+} from '@librechat/agents';+import type { CodeExecutionContext } from '../execution';+import type { ToolExecuteOptions } from '../handlers';+import { createToolExecuteHandler } from '../handlers';++const identity: SubagentExecutionContext = {+ rootRunId: 'run',+ hookSessionId: 'run',+ depth: 1,+ ancestry: [+ {+ subagentRunId: 'child-execution',+ subagentType: 'worker',+ subagentKind: 'agent',+ subagentAgentId: 'worker',+ parentRunId: 'run',+ parentAgentId: 'parent',+ parentToolCallId: 'spawn-call',+ },+ ],+};++function setup(context?: Partial<CodeExecutionContext>, toolName = 'execute_code') {+ const signal = new AbortController().signal;+ const calls: string[] = [];+ const prepareTools = jest.fn(async () => {+ calls.push('prepare');+ });+ const provisionFiles = jest.fn(async () => {+ calls.push('provision');+ });+ const loadedTool = tool(async () => '', {+ name: toolName,+ description: 'Execute code',+ schema: z.object({ code: z.string() }),+ });+ const invoke = jest.spyOn(loadedTool, 'invoke').mockImplementation(async () => {+ calls.push('invoke');+ return new ToolMessage({+ content: 'Created results.csv',+ tool_call_id: 'code-call',+ artifact: { session_id: 'child-sandbox', files: [{ id: 'output', name: 'results.csv' }] },+ });+ });+ const loadTools = jest.fn<+ ReturnType<ToolExecuteOptions['loadTools']>,+ Parameters<ToolExecuteOptions['loadTools']>+ >(async () => {+ calls.push('load');+ return {+ loadedTools: [loadedTool],+ configurable: {+ executionContext: { spoofed: true },+ codeExecutionContext: {+ baseUrl: 'https://sandbox.invalid',+ codeSessionKey: 'private-child-partition',+ runtimeSessionHint: 'private-child-runtime',+ executionProfile: 'stateful',+ statefulSessions: true,+ ...context,+ },+ },+ };+ });+ const toolEndCallback = jest.fn(async () => {+ calls.push('capture');+ });+ let queue = Promise.resolve();+ const withCodeExecution: NonNullable<ToolExecuteOptions['runFiles']>['withCodeExecution'] = (+ _agentId,+ _context,+ _signal,+ execute,+ ) => {+ const result = queue.then(async () => {+ calls.push('enter');+ try {+ return await execute();+ } finally {+ calls.push('leave');+ }+ });+ queue = result.then(+ () => undefined,+ () => undefined,+ );+ return result;+ };+ const handler = createToolExecuteHandler({+ runFiles: { isActive: () => true, prepareTools, withCodeExecution },+ loadTools,+ provisionFiles,+ toolEndCallback,+ });+ const execute = (+ executionContext = identity,+ toolCalls: ToolExecuteBatchRequest['toolCalls'] = [+ {+ id: 'code-call',+ name: toolName,+ args: { code: 'print("results")' },+ runtimeSessionHint: 'parent-runtime',+ },+ ],+ ) =>+ new Promise<ToolExecuteResult[]>((resolve, reject) => {+ const request = {+ agentId: 'worker',+ executionContext,+ configurable: { run_id: 'run', executionContext: { inherited: true } },+ metadata: { run_id: 'run', executionContext: { inherited: true } },+ toolCalls,+ signal,+ resolve,+ reject,+ } as ToolExecuteBatchRequest & { executionContext: SubagentExecutionContext };+ void handler.handle('on_tool_execute', request);+ });+ return {+ execute,+ calls,+ signal,+ prepareTools,+ provisionFiles,+ loadTools,+ invoke,+ toolEndCallback,+ };+}++describe('shared-file event execution identity', () => {+ it('authorizes before provisioning and overwrites inherited tool and artifact identities', async () => {+ const test = setup();+ expect((await test.execute())[0].status).toBe('success');+ expect(test.calls).toEqual([+ 'prepare',+ 'provision',+ 'load',+ 'enter',+ 'invoke',+ 'capture',+ 'leave',+ ]);+ expect(test.prepareTools).toHaveBeenCalledWith('worker', identity, test.signal, 'refresh');+ expect(test.provisionFiles).toHaveBeenCalledWith(+ ['execute_code'],+ 'worker',+ test.signal,+ identity,+ );+ expect(test.loadTools).toHaveBeenCalledWith(+ ['execute_code'],+ 'worker',+ expect.objectContaining({ executionContext: identity }),+ undefined,+ test.signal,+ identity,+ );+ expect(test.invoke).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ configurable: expect.objectContaining({ executionContext: identity }),+ metadata: expect.objectContaining({ executionContext: identity }),+ toolCall: expect.objectContaining({ _runtime_session_hint: 'private-child-runtime' }),+ }),+ );+ expect(test.toolEndCallback).toHaveBeenCalledWith(+ expect.objectContaining({+ output: expect.objectContaining({ artifact: expect.any(Object) }),+ }),+ expect.objectContaining({ executionContext: identity, executingAgentId: 'worker' }),+ );+ });++ it.each(['calculator', 'web_search', 'weather_mcp_example'])(+ 'prepares the authorized snapshot before unrelated %s batches execute',+ async (toolName) => {+ const test = setup(undefined, toolName);+ expect((await test.execute())[0].status).toBe('success');+ expect((await test.execute())[0].status).toBe('success');+ expect(test.prepareTools).toHaveBeenCalledTimes(2);+ expect(test.prepareTools).toHaveBeenCalledWith('worker', identity, test.signal, 'snapshot');+ expect(test.calls.slice(0, 4)).toEqual(['prepare', 'provision', 'load', 'invoke']);+ expect(test.calls).not.toContain('enter');+ },+ );++ it.each([+ 'execute_code',+ 'bash_tool',+ 'run_tools_with_code',+ 'run_tools_with_bash',+ 'create_file',+ 'edit_file',+ 'read_file',+ 'write_file',+ 'search_workspace',+ 'list_workspace_files',+ 'file_search',+ 'image_gen_oai',+ 'image_edit_oai',+ 'gemini_image_gen',+ ])('refreshes publications before the %s file consumer loads', async (toolName) => {+ const test = setup(undefined, toolName);+ test.prepareTools.mockRejectedValueOnce(new Error('Publication refresh failed'));+ await expect(test.execute()).rejects.toThrow('Publication refresh failed');+ expect(test.prepareTools).toHaveBeenCalledWith('worker', identity, test.signal, 'refresh');+ expect(test.provisionFiles).not.toHaveBeenCalled();+ expect(test.loadTools).not.toHaveBeenCalled();+ });++ it('refreshes a mixed batch before either unrelated or file-consuming tools load', async () => {+ const test = setup();+ test.prepareTools.mockRejectedValueOnce(new Error('Publication refresh failed'));+ await expect(+ test.execute(identity, [+ { id: 'search', name: 'web_search', args: { query: 'related work' } },+ { id: 'files', name: 'file_search', args: { query: 'uploaded report' } },+ ]),+ ).rejects.toThrow('Publication refresh failed');+ expect(test.prepareTools).toHaveBeenCalledWith('worker', identity, test.signal, 'refresh');+ expect(test.loadTools).not.toHaveBeenCalled();+ });++ it.each(['execute_code', 'calculator'])(+ 'stops before loading or executing %s when the child grant is denied',+ async (toolName) => {+ const test = setup(undefined, toolName);+ test.prepareTools.mockRejectedValueOnce(new Error('Execution grant denied'));+ await expect(test.execute()).rejects.toThrow('Execution grant denied');+ expect(test.provisionFiles).not.toHaveBeenCalled();+ expect(test.loadTools).not.toHaveBeenCalled();+ expect(test.invoke).not.toHaveBeenCalled();+ },+ );++ it('holds the code queue through artifact capture before another call can mutate the sandbox', async () => {+ const test = setup();+ let finishCapture: () => void = () => undefined;+ const captured = new Promise<void>((resolve) => {+ finishCapture = resolve;+ });+ let captureStarted: () => void = () => undefined;+ const started = new Promise<void>((resolve) => {+ captureStarted = resolve;+ });+ test.toolEndCallback.mockImplementationOnce(async () => {+ test.calls.push('capture');+ captureStarted();+ await captured;+ });+ const completion = test.execute(identity, [+ { id: 'one', name: 'execute_code', args: { code: 'first' } },+ { id: 'two', name: 'execute_code', args: { code: 'second' } },+ ]);+ await started;+ expect(test.invoke).toHaveBeenCalledTimes(1);+ expect(test.calls).not.toContain('leave');+ finishCapture();+ expect((await completion).map((result) => result.status)).toEqual(['success', 'success']);+ expect(test.calls.slice(3)).toEqual([+ 'enter',+ 'invoke',+ 'capture',+ 'leave',+ 'enter',+ 'invoke',+ 'capture',+ 'leave',+ ]);+ });++ it('rejects background code before it can bypass the file generation queue', async () => {+ const test = setup();+ const [result] = await test.execute(identity, [+ {+ id: 'background',+ name: 'execute_code',+ args: { code: 'write()', run_in_background: true },+ },+ ]);+ expect(result.status).toBe('error');+ expect(result.errorMessage).toContain('foreground execution');+ expect(test.invoke).not.toHaveBeenCalled();+ expect(test.toolEndCallback).not.toHaveBeenCalled();+ });++ it.each([{ runtimeSessionHint: undefined }, { environmentType: 'attached' as const }])(+ 'fails closed without a managed child sandbox (%j)',+ async (context) => {+ const test = setup(context);+ await expect(test.execute()).rejects.toThrow('no isolated file workspace');+ expect(test.invoke).not.toHaveBeenCalled();+ expect(test.toolEndCallback).not.toHaveBeenCalled();+ },+ );+});diff --git a/packages/api/src/agents/files/host.spec.ts b/packages/api/src/agents/files/host.spec.tsnew file mode 100644index 0000000000..c557cb5340--- /dev/null+++ b/packages/api/src/agents/files/host.spec.ts@@ -0,0 +1,848 @@+import { Constants } from '@librechat/agents';+import {+ AgentCapabilities,+ EToolResources,+ FileContext,+ FileSources,+ configSchema,+} from 'librechat-data-provider';+import type { Agent, CodeEnvRef, TFile } from 'librechat-data-provider';+import type { SubagentExecutionContext } from '@librechat/agents';+import type { ProvisionCallbackDeps } from '~/files/provision/callback';+import type { RunFileSessionDeps } from './session';+import type { RunFileToolContext } from './host';+import type { ServerRequest } from '~/types';+import { createRunFileHost, resolveRunFileCodeExecutionContext } from './host';+import * as sessionModule from './session';++jest.mock('@librechat/data-schemas', () => ({+ logger: { error: jest.fn(), warn: jest.fn(), debug: jest.fn(), info: jest.fn() },+}));++function file(id: string, overrides: Partial<TFile> = {}): TFile {+ return {+ file_id: id,+ filename: `${id}.csv`,+ filepath: `/uploads/${id}.csv`,+ user: 'user',+ tenantId: 'tenant',+ type: 'text/csv',+ bytes: 12,+ embedded: false,+ object: 'file',+ usage: 0,+ source: FileSources.local,+ context: FileContext.message_attachment,+ llmDeliveryPath: 'none',+ metadata: { destinationChosen: false },+ ...overrides,+ };+}++function identity(id = 'child'): SubagentExecutionContext {+ return {+ rootRunId: 'run',+ hookSessionId: 'run',+ depth: 1,+ ancestry: [+ {+ subagentRunId: id,+ subagentType: 'worker',+ subagentKind: 'agent',+ subagentAgentId: 'worker',+ parentRunId: 'run',+ parentAgentId: 'parent',+ parentToolCallId: `spawn-${id}`,+ },+ ],+ };+}++function deferred<T>() {+ let resolve!: (value: T | PromiseLike<T>) => void;+ let reject!: (reason?: unknown) => void;+ const promise = new Promise<T>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ return { promise, resolve, reject };+}++function harness(options: { inputs?: TFile[]; setup?: TFile[] } = {}) {+ const input = options.inputs ?? [file('input')];+ const setup = options.setup ?? [file('worker-setup', { context: FileContext.agents })];+ const parsed = configSchema.parse({+ version: '1.3.9',+ endpoints: {+ agents: {+ capabilities: [AgentCapabilities.context],+ fileSharing: { enabled: true },+ },+ },+ });+ const req = {+ user: { id: 'user', tenantId: 'tenant', role: 'USER' },+ config: { endpoints: { agents: parsed.endpoints?.agents } },+ } as ServerRequest;+ const agent = (id: string): Agent =>+ ({+ id,+ name: id,+ provider: 'openAI',+ model: 'gpt-4o',+ tools: [Constants.EXECUTE_CODE, EToolResources.file_search, EToolResources.context],+ tool_resources:+ id === 'worker'+ ? {+ execute_code: { file_ids: setup.map((entry) => entry.file_id) },+ file_search: { file_ids: setup.map((entry) => entry.file_id) },+ }+ : undefined,+ subagents: { enabled: true, shareFiles: true, allowSelf: false, agent_ids: ['worker'] },+ }) as Agent;+ const contexts = new Map<string, RunFileToolContext>(+ ['parent', 'worker'].map((id) => [+ id,+ {+ agent: agent(id),+ codeEnvAvailable: true,+ // Base initialization may contain historical runtime resources. Only persisted+ // setup membership and this run's manifest may reach an execution host.+ tool_resources: { execute_code: { files: [file('historical')] } },+ codeExecutionContext: {+ baseUrl: 'https://code.example',+ executionProfile: 'stateful',+ executionRouteKey: 'managed-worker',+ environmentType: 'managed',+ codeSessionKey: 'base-agent-session',+ runtimeSessionHint: 'base-agent-session',+ statefulSessions: true,+ },+ },+ ]),+ );+ const loadFiles = jest.fn(async (_ids: string[]) => structuredClone(setup));+ const filterFiles = jest.fn(async ({ files }: { files: TFile[] }) => files);+ const saved: TFile[] = [];+ const listPublications = jest.fn(async () => structuredClone(saved));+ const publish = jest.fn<+ ReturnType<RunFileSessionDeps['publish']>,+ Parameters<RunFileSessionDeps['publish']>+ >(async ({ scope, artifact, provenance }) => {+ const published = file(`published-${provenance.sourceFileId}`, {+ filename: artifact.name,+ conversationId: scope.conversationId,+ context: FileContext.run_artifact,+ metadata: { destinationChosen: false, runFile: provenance },+ });+ saved.push(published);+ return structuredClone(published);+ });+ type CodeProvision = ProvisionCallbackDeps['provisionToCodeEnv'];+ const codeResult = ({+ file: candidate,+ entity_id,+ sandboxFilename,+ route,+ }: Parameters<CodeProvision>[0]): Awaited<ReturnType<CodeProvision>> => {+ const routeKey = route?.executionRouteKey ?? route?.executionProfile ?? 'default';+ const ref: CodeEnvRef = {+ kind: entity_id ? 'agent' : 'user',+ id: entity_id ?? 'user',+ file_id: `remote-${candidate.file_id}`,+ storage_session_id: `storage-${entity_id ?? 'user'}`,+ sandboxFilename,+ };+ return {+ referenceSet: { codeEnvRefs: { [routeKey]: ref } },+ refUpdate: { file_id: candidate.file_id, routeKey, ref },+ sandboxFilename: sandboxFilename ?? candidate.filename,+ };+ };+ const provisionToCodeEnv = jest.fn<ReturnType<CodeProvision>, Parameters<CodeProvision>>(+ async (params) => codeResult(params),+ );+ const provisionToVectorDB = jest.fn<+ ReturnType<ProvisionCallbackDeps['provisionToVectorDB']>,+ Parameters<ProvisionCallbackDeps['provisionToVectorDB']>+ >(async ({ file: candidate }) => ({+ embedded: true,+ fileUpdate: { file_id: candidate.file_id, embedded: true },+ }));+ const updateCodeEnvRef = jest.fn(async () => undefined);+ const addEmbeddedEntity = jest.fn(async () => undefined);+ const emit = jest.fn(async () => undefined);+ const encodeMessages = jest.fn(async () => []);+ const spy = jest.spyOn(sessionModule, 'createRunFileSession');+ const host = createRunFileHost({+ req,+ contexts,+ createdAt: Date.now(),+ inputFileIds: new Set(input.map((entry) => entry.file_id)),+ getInputs: () => [...input, file('foreign-history', { user: 'other' })],+ loadFiles,+ filterFiles,+ listPublications,+ snapshots: {+ capture: jest.fn(async () => ({ snapshotId: 'private-output', size: 12, sha256: 'hash' })),+ discard: jest.fn(async () => undefined),+ close: jest.fn(async () => undefined),+ },+ publish,+ emit,+ validateMessages: jest.fn(),+ encodeMessages,+ provisioning: {+ provisionToCodeEnv,+ provisionToVectorDB,+ updateCodeEnvRef,+ updateFile: jest.fn(async () => undefined),+ addEmbeddedEntity,+ },+ });+ const deps = spy.mock.calls[spy.mock.calls.length - 1][0];+ host.session.activate('run', 'conversation', ['parent']);+ const signal = new AbortController().signal;+ const prepare = (context = identity(), suppliedSignal = signal) =>+ host.session.prepare({+ executionContext: context,+ memberAgentIds: ['worker'],+ signal: suppliedSignal,+ resumed: false,+ });+ const publishOutput = async (context = identity(), id = 'output') => {+ await host.session.capture(+ 'worker',+ context,+ `tool-${id}`,+ {+ session_id: `private-${context.ancestry[0].subagentRunId}`,+ files: [{ id, name: `${id}.csv` }],+ },+ host.getContext('worker', context)?.codeExecutionContext,+ );+ const artifact = (await host.session.list('worker', context)).artifacts.find(+ (entry) => entry.filename === `${id}.csv`,+ );+ if (!artifact) throw new Error('Expected staged artifact');+ return host.session.publish('worker', context, artifact.artifact_id, [], signal);+ };+ return {+ host,+ deps,+ req,+ contexts,+ input,+ setup,+ saved,+ signal,+ prepare,+ publishOutput,+ loadFiles,+ filterFiles,+ publish,+ emit,+ encodeMessages,+ listPublications,+ provisionToCodeEnv,+ provisionToVectorDB,+ updateCodeEnvRef,+ addEmbeddedEntity,+ codeResult,+ };+}++describe('run file execution host', () => {+ afterEach(() => jest.restoreAllMocks());++ it.each([+ ['file_search', { file_search: { citations: ['document'] } }],+ ['web_search', { web_search: { results: ['page'] } }],+ ['set_memory', { memory: { key: 'preference', value: 'saved' } }],+ ['interactive_tool', { ui_resources: { data: ['widget'] } }],+ [+ 'generate_image',+ { content: [{ type: 'image_url', image_url: { url: 'data:image/png;base64,aQ==' } }] },+ ],+ ])('preserves ordinary %s artifact delivery from a shared-file child', async (name, artifact) => {+ const h = harness();+ await h.prepare();+ const callback = jest.fn(async () => undefined);+ const data = { output: { name, tool_call_id: 'other-output', content: '', artifact } };+ const metadata = { executingAgentId: 'worker', executionContext: identity() };++ await h.host.deliverToolEnd(callback, data, metadata);++ expect(callback).toHaveBeenCalledWith(data, metadata);+ expect(h.deps.snapshots.capture).not.toHaveBeenCalled();+ expect((await h.host.session.list('worker', identity())).artifacts).toEqual([]);+ });++ it.each(['execute_code', 'bash_tool', 'create_file'])(+ 'keeps %s outputs private until publication',+ async (name) => {+ const h = harness();+ await h.prepare();+ const callback = jest.fn(async () => undefined);+ await h.host.deliverToolEnd(+ callback,+ {+ output: {+ name,+ tool_call_id: 'private-output',+ content: '',+ artifact: {+ session_id: 'sandbox',+ files: [{ id: 'chart', name: 'chart.png' }],+ },+ },+ },+ { executingAgentId: 'worker', executionContext: identity() },+ );++ expect(callback).not.toHaveBeenCalled();+ expect(h.emit).not.toHaveBeenCalled();+ expect((await h.host.session.list('worker', identity())).artifacts).toEqual([+ { artifact_id: expect.any(String), filename: 'chart.png' },+ ]);+ const [artifact] = (await h.host.session.list('worker', identity())).artifacts;+ await h.host.session.publish('worker', identity(), artifact.artifact_id, [], h.signal);+ expect(h.emit).toHaveBeenCalledTimes(1);+ },+ );++ it('does not publish a private sandbox image merely because the child reads it', async () => {+ const h = harness();+ await h.prepare();+ const callback = jest.fn(async () => undefined);+ const artifact = {+ content: [{ type: 'image_url', image_url: { url: 'data:image/png;base64,aQ==' } }],+ };+ const data = {+ output: { name: 'read_file', tool_call_id: 'inspect-image', content: 'Image', artifact },+ };++ await h.host.deliverToolEnd(callback, data, {+ executingAgentId: 'worker',+ executionContext: identity(),+ });++ expect(callback).not.toHaveBeenCalled();+ expect(h.emit).not.toHaveBeenCalled();+ expect(h.deps.snapshots.capture).not.toHaveBeenCalled();+ expect(data.output.artifact).toBe(artifact);+ });++ it('reuses the handler authorized batch without a second publication query', async () => {+ const h = harness();+ await expect(+ h.host.provisionPrepared([Constants.EXECUTE_CODE], 'parent', h.signal),+ ).rejects.toThrow('not been prepared');+ await h.prepare();+ await h.host.session.prepareTools('worker', identity(), h.signal);+ const reads = h.listPublications.mock.calls.length;+ await h.host.provisionPrepared([Constants.EXECUTE_CODE], 'worker', h.signal, identity());+ expect(h.listPublications).toHaveBeenCalledTimes(reads);+ expect(h.provisionToCodeEnv).toHaveBeenCalledTimes(2);+ });++ it('keeps current inputs user-scoped and each agent setup agent-scoped without historical files', async () => {+ const current = file('current', { context: FileContext.agents });+ const h = harness({ inputs: [current] });+ h.loadFiles.mockResolvedValue([...h.setup, file('unrequested-setup', { user: 'other' })]);+ await h.prepare();+ await h.host.provision([Constants.EXECUTE_CODE, 'file_search'], 'worker', h.signal, identity());+ expect(h.loadFiles).toHaveBeenCalledWith(['worker-setup']);+ expect(h.filterFiles).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'worker', userId: 'user' }),+ );+ const codeCalls = h.provisionToCodeEnv.mock.calls.map(([params]) => [+ params.file.file_id,+ params.entity_id,+ ]);+ expect(codeCalls).toEqual(+ expect.arrayContaining([+ ['current', undefined],+ ['worker-setup', 'worker'],+ ]),+ );+ expect(codeCalls).toHaveLength(2);+ expect(+ h.provisionToVectorDB.mock.calls.map(([params]) => [params.file.file_id, params.entity_id]),+ ).toEqual(+ expect.arrayContaining([+ ['current', undefined],+ ['worker-setup', 'worker'],+ ]),+ );+ const context = h.host.getContext('worker', identity());+ expect(+ context?.tool_resources?.execute_code?.files?.map((entry) => entry.file_id).sort(),+ ).toEqual(['current', 'worker-setup']);+ expect(context?.tool_resources?.file_search?.file_ids).toEqual(['worker-setup']);+ expect(context?.provisionState?.agentScopedFileIds).toEqual(new Set(['worker-setup']));+ expect(current.metadata?.codeEnvRefs).toBeUndefined();+ expect(+ h.contexts.get('worker')?.tool_resources?.execute_code?.files?.map((entry) => entry.file_id),+ ).toEqual(['historical']);+ });++ it('isolates concurrent executions of the same agent without broadening storage grants', async () => {+ const h = harness();+ const first = identity('first');+ const second = identity('second');+ const results = await Promise.all([h.prepare(first), h.prepare(second)]);+ const a = h.host.getContext('worker', first)!;+ const b = h.host.getContext('worker', second)!;+ expect(a).not.toBe(b);+ expect(a.provisionState?.codeEnvFiles[0]).not.toBe(b.provisionState?.codeEnvFiles[0]);+ expect(a.codeExecutionContext?.codeSessionKey).not.toBe(b.codeExecutionContext?.codeSessionKey);+ expect(a.codeExecutionContext?.runtimeSessionHint).toBe(a.codeExecutionContext?.codeSessionKey);+ expect(b.codeExecutionContext?.runtimeSessionHint).toBe(b.codeExecutionContext?.codeSessionKey);+ expect(results[0].agentSessions?.worker.codeSessionKey).toBe(+ a.codeExecutionContext?.codeSessionKey,+ );+ expect(results[1].agentSessions?.worker.codeSessionKey).toBe(+ b.codeExecutionContext?.codeSessionKey,+ );+ await Promise.all(+ [first, second].map((context) =>+ h.host.provision([Constants.EXECUTE_CODE], 'worker', h.signal, context),+ ),+ );+ expect(h.provisionToCodeEnv.mock.calls.map(([params]) => params.entity_id)).toEqual(+ expect.arrayContaining([undefined, 'worker']),+ );+ expect(+ h.provisionToCodeEnv.mock.calls.every(+ ([params]) => params.entity_id == null || params.entity_id === 'worker',+ ),+ ).toBe(true);+ expect(h.contexts.get('worker')?.codeExecutionContext?.codeSessionKey).toBe(+ 'base-agent-session',+ );+ });++ it('refreshes after publication while retaining successful resources, context and setup hydration', async () => {+ const h = harness();+ await h.prepare();+ await h.host.provision([Constants.EXECUTE_CODE, 'file_search'], 'worker', h.signal, identity());+ const before = h.host.getContext('worker', identity());+ const published = await h.publishOutput();+ await h.host.provision([Constants.EXECUTE_CODE, 'file_search'], 'worker', h.signal, identity());+ expect(h.host.getContext('worker', identity())).toBe(before);+ expect(+ before?.tool_resources?.execute_code?.files?.map((entry) => entry.file_id).sort(),+ ).toEqual(['input', published.file_id, 'worker-setup'].sort());+ expect(h.provisionToCodeEnv).toHaveBeenCalledTimes(3);+ expect(h.provisionToVectorDB).toHaveBeenCalledTimes(3);+ expect(h.loadFiles).toHaveBeenCalledTimes(1);+ expect(h.emit).toHaveBeenCalledTimes(1);+ expect(h.publish).toHaveBeenCalledWith(+ expect.objectContaining({+ artifact: expect.objectContaining({ sessionId: 'private-child' }),+ provenance: expect.objectContaining({+ agentId: 'worker',+ executionId: 'child',+ parentExecutionId: 'run',+ }),+ }),+ );+ });++ it('does not provision private staged outputs before explicit publication', async () => {+ const h = harness({ setup: [] });+ await h.prepare();+ await h.host.session.capture('worker', identity(), 'private-call', {+ session_id: 'private-child',+ files: [{ id: 'private-file', name: 'private.csv' }],+ });+ await h.host.provision([Constants.EXECUTE_CODE], 'worker', h.signal, identity());+ expect(h.provisionToCodeEnv.mock.calls.map(([params]) => params.file.file_id)).toEqual([+ 'input',+ ]);+ expect(h.publish).not.toHaveBeenCalled();+ expect(h.emit).not.toHaveBeenCalled();+ });++ it('preserves the root historical resources and runtime while descendants receive current inputs', async () => {+ const h = harness();+ const root = h.contexts.get('parent')!;+ root.tool_resources!.file_search = { file_ids: ['parent-setup'] };+ root.provisionState = {+ codeEnvFiles: [file('historical-deferred')],+ vectorDBFiles: [],+ aliveFileIds: new Set(),+ agentScopedFileIds: new Set(['parent-setup']),+ };+ const originalCodeContext = root.codeExecutionContext;+ await h.prepare();+ await h.host.provision([Constants.EXECUTE_CODE], 'parent', h.signal);+ const published = await h.publishOutput();+ await h.host.provision([Constants.EXECUTE_CODE], 'parent', h.signal);+ expect(h.host.getContext('parent')).toBe(root);+ expect(root.codeExecutionContext).toBe(originalCodeContext);+ expect(root.codeExecutionContext?.codeSessionKey).toBe('base-agent-session');+ expect(root.tool_resources?.file_search?.file_ids).toEqual(['parent-setup']);+ expect(root.tool_resources?.execute_code?.files?.map((entry) => entry.file_id).sort()).toEqual(+ ['historical', 'historical-deferred', 'input', published.file_id].sort(),+ );+ expect(+ h.host+ .getContext('worker', identity())+ ?.provisionState?.codeEnvFiles.map((entry) => entry.file_id)+ .sort(),+ ).toEqual(['input', 'worker-setup']);+ expect(+ h.provisionToCodeEnv.mock.calls.filter(+ ([params]) => params.file.file_id === 'historical-deferred',+ ),+ ).toHaveLength(1);+ expect(h.loadFiles).toHaveBeenCalledTimes(1);+ });++ it('keeps successful refs across a partial failure, publication refresh and retry', async () => {+ const h = harness({ inputs: [file('good'), file('retry')], setup: [] });+ let fail = true;+ h.provisionToCodeEnv.mockImplementation(async (params) => {+ if (params.file.file_id === 'retry' && fail) throw new Error('Temporary Code API outage');+ return h.codeResult(params);+ });+ await h.prepare();+ await expect(+ h.host.provision([Constants.EXECUTE_CODE], 'worker', h.signal, identity()),+ ).rejects.toThrow('Failed to provision');+ const before = h.host.getContext('worker', identity());+ expect(before?.pendingProvisionedCodeFiles?.map((entry) => entry.id)).toEqual(['remote-good']);+ const published = await h.publishOutput();+ fail = false;+ const recovered = await h.host.provision(+ [Constants.EXECUTE_CODE],+ 'worker',+ h.signal,+ identity(),+ );+ expect(h.host.getContext('worker', identity())).toBe(before);+ expect(recovered?.map((entry) => entry.id).sort()).toEqual(+ ['remote-good', 'remote-retry', `remote-${published.file_id}`].sort(),+ );+ expect(+ h.provisionToCodeEnv.mock.calls.filter(([params]) => params.file.file_id === 'good'),+ ).toHaveLength(1);+ expect(before?.provisionState?.codeEnvFiles).toEqual([]);+ });++ it('rejects an older snapshot arriving after a newer grant removal', async () => {+ const h = harness({ setup: [] });+ await h.prepare();+ const published = await h.publishOutput();+ const context = h.host.getContext('worker', identity());+ const actor = h.host.session.actorFor('worker', identity());+ const sessionKey = context!.codeExecutionContext!.codeSessionKey;+ await h.deps.prepareAgent({+ actor,+ files: [...h.input, published],+ sessionKey,+ revision: 5,+ signal: h.signal,+ });+ await h.deps.prepareAgent({ actor, files: h.input, sessionKey, revision: 6, signal: h.signal });+ await h.deps.prepareAgent({+ actor,+ files: [...h.input, published],+ sessionKey,+ revision: 4,+ signal: h.signal,+ });+ expect(h.host.getContext('worker', identity())).toBe(context);+ expect(context?.provisionState?.codeEnvFiles.map((entry) => entry.file_id)).toEqual(['input']);+ });++ it('joins an in-flight refresh before a later snapshot can retain a deleted publication', async () => {+ const h = harness({ setup: [] });+ const read = deferred<TFile[]>();+ try {+ await h.prepare();+ const published = await h.publishOutput();+ await h.host.session.prepareTools('worker', identity(), h.signal);+ const context = h.host.getContext('worker', identity());+ expect(context?.provisionState?.codeEnvFiles.map((entry) => entry.file_id)).toContain(+ published.file_id,+ );+ h.saved.splice(0);+ h.listPublications.mockImplementationOnce(() => read.promise);+ const reads = h.listPublications.mock.calls.length;+ const refreshed = h.host.session.prepareTools('worker', identity(), h.signal);+ let snapshotSettled = false;+ const snapshot = h.host.session+ .prepareTools('worker', identity(), h.signal, 'snapshot')+ .then(() => {+ snapshotSettled = true;+ });+ await new Promise<void>((resolve) => setImmediate(resolve));+ const settledBeforeRead = snapshotSettled;+ read.resolve([]);+ await Promise.all([refreshed, snapshot]);++ const provisioned = await h.host.provisionPrepared(+ [Constants.EXECUTE_CODE],+ 'worker',+ h.signal,+ identity(),+ );+ expect(settledBeforeRead).toBe(false);+ expect(h.listPublications).toHaveBeenCalledTimes(reads + 1);+ expect(h.host.getContext('worker', identity())).toBe(context);+ expect(provisioned?.map((entry) => entry.id)).toEqual(['remote-input']);+ expect(context?.tool_resources?.execute_code?.files?.map((entry) => entry.file_id)).toEqual([+ 'input',+ ]);+ } finally {+ read.resolve([]);+ await h.host.session.close();+ }+ });++ it('serializes preparation with provisioning without blocking another execution', async () => {+ const h = harness({ setup: [] });+ const first = identity('first');+ const second = identity('second');+ await Promise.all([h.prepare(first), h.prepare(second)]);+ const entered = deferred<void>();+ const finish = deferred<void>();+ h.provisionToCodeEnv.mockImplementationOnce(async (params) => {+ entered.resolve();+ await finish.promise;+ return h.codeResult(params);+ });+ const upload = h.host.provision([Constants.EXECUTE_CODE], 'worker', h.signal, first);+ await entered.promise;+ const before = h.host.getContext('worker', first)!;+ let refreshed = false;+ const refresh = h.deps+ .prepareAgent({+ actor: h.host.session.actorFor('worker', first),+ files: [...h.input, file('new')],+ sessionKey: before.codeExecutionContext!.codeSessionKey,+ revision: 100,+ signal: h.signal,+ })+ .then(() => {+ refreshed = true;+ });+ await h.host.provision([Constants.EXECUTE_CODE], 'worker', h.signal, second);+ expect(refreshed).toBe(false);+ finish.resolve();+ await Promise.all([upload, refresh]);+ expect(h.host.getContext('worker', first)).toBe(before);+ expect(before.tool_resources?.execute_code?.files?.map((entry) => entry.file_id)).toEqual([+ 'input',+ ]);+ expect(before.provisionState?.codeEnvFiles.map((entry) => entry.file_id)).toEqual(['new']);+ });++ it('fails a setup load closed while another execution and a later retry succeed', async () => {+ const h = harness();+ h.loadFiles.mockRejectedValueOnce(new Error('Setup load failed'));+ const results = await Promise.allSettled([+ h.prepare(identity('first')),+ h.prepare(identity('second')),+ ]);+ expect(results.map((result) => result.status)).toEqual(['rejected', 'fulfilled']);+ expect(h.host.getContext('worker', identity('first'))).toBeUndefined();+ expect(h.host.getContext('worker', identity('second'))).toBeDefined();+ expect(h.provisionToCodeEnv).not.toHaveBeenCalled();+ await h.prepare(identity('first'));+ await h.host.provision([Constants.EXECUTE_CODE], 'worker', h.signal, identity('first'));+ expect(h.provisionToCodeEnv).toHaveBeenCalledTimes(2);+ });++ it('fails access errors closed and removes denied setup ids from runtime resources', async () => {+ const h = harness();+ h.filterFiles.mockRejectedValueOnce(new Error('ACL unavailable'));+ await expect(h.prepare()).rejects.toThrow('ACL unavailable');+ expect(h.host.getContext('worker', identity())).toBeUndefined();+ h.filterFiles.mockResolvedValue([]);+ await h.prepare();+ const context = h.host.getContext('worker', identity());+ expect(context?.tool_resources?.execute_code?.file_ids).toEqual([]);+ expect(context?.tool_resources?.file_search?.file_ids).toEqual([]);+ expect(context?.provisionState?.agentScopedFileIds).toEqual(new Set());+ await h.host.provision([Constants.EXECUTE_CODE], 'worker', h.signal, identity());+ expect(h.provisionToCodeEnv.mock.calls.map(([params]) => params.file.file_id)).toEqual([+ 'input',+ ]);+ });++ it('applies one endpoint size budget to current inputs and setup files', async () => {+ const h = harness({+ inputs: [file('input', { bytes: 600_000 })],+ setup: [file('worker-setup', { bytes: 600_000, context: FileContext.agents })],+ });+ if (!h.req.config) throw new Error('Missing test configuration');+ h.req.config.fileConfig = { endpoints: { openAI: { totalSizeLimit: 1 } } };+ await expect(h.prepare()).rejects.toThrow('not supported by the receiving agent');+ expect(h.host.getContext('worker', identity())).toBeUndefined();+ expect(h.provisionToCodeEnv).not.toHaveBeenCalled();+ });++ it.each(['resource', 'code queue', 'search queue'] as const)(+ 'includes retained root files from the %s in the shared-file budget',+ async (location) => {+ const h = harness({ inputs: [file('input', { bytes: 600_000 })], setup: [] });+ h.req.config!.fileConfig = { endpoints: { openAI: { totalSizeLimit: 1 } } };+ const retained = file('retained', { bytes: 600_000 });+ const root = h.contexts.get('parent')!;+ root.tool_resources = {+ execute_code: { files: location === 'resource' ? [retained] : [] },+ };+ root.provisionState = {+ codeEnvFiles: location === 'code queue' ? [retained] : [],+ vectorDBFiles: location === 'search queue' ? [retained] : [],+ aliveFileIds: new Set(),+ agentScopedFileIds: new Set(),+ };+ const resources = structuredClone(root.tool_resources);+ const queues = structuredClone({+ codeEnvFiles: root.provisionState.codeEnvFiles,+ vectorDBFiles: root.provisionState.vectorDBFiles,+ });+ try {+ await expect(h.host.session.prepareTools('parent', undefined, h.signal)).rejects.toThrow(+ 'not supported by the receiving agent',+ );+ expect(root.tool_resources).toEqual(resources);+ expect(root.provisionState).toMatchObject(queues);+ expect(h.provisionToCodeEnv).not.toHaveBeenCalled();+ expect(h.loadFiles).not.toHaveBeenCalled();++ retained.bytes = 400_000;+ await h.host.session.prepareTools('parent', undefined, h.signal);+ expect(root.provisionState?.codeEnvFiles.map((entry) => entry.file_id)).toContain('input');+ } finally {+ await h.host.session.close();+ }+ },+ );++ it('counts retained root files once across resources, queues and the current manifest', async () => {+ const current = file('input', { bytes: 600_000 });+ const retained = file('retained', { bytes: 400_000 });+ const h = harness({ inputs: [current], setup: [] });+ h.req.config!.fileConfig = { endpoints: { openAI: { totalSizeLimit: 1 } } };+ const root = h.contexts.get('parent')!;+ root.tool_resources = {+ execute_code: { files: [retained, current] },+ file_search: { files: [retained] },+ };+ root.provisionState = {+ codeEnvFiles: [retained, current],+ vectorDBFiles: [retained],+ aliveFileIds: new Set(),+ agentScopedFileIds: new Set(),+ };+ try {+ await h.host.session.prepareTools('parent', undefined, h.signal);+ await h.host.session.prepareTools('parent', undefined, h.signal);+ expect(root.provisionState.codeEnvFiles.map((entry) => entry.file_id)).toEqual([+ 'retained',+ 'input',+ ]);++ root.provisionState.vectorDBFiles.push(file('later-setup', { bytes: 100_000 }));+ await expect(h.host.session.prepareTools('parent', undefined, h.signal)).rejects.toThrow(+ 'not supported by the receiving agent',+ );+ } finally {+ await h.host.session.close();+ }+ });++ it('releases the root budget when a previous publication is removed', async () => {+ const h = harness({ inputs: [], setup: [] });+ h.req.config!.fileConfig = { endpoints: { openAI: { totalSizeLimit: 1 } } };+ const root = h.contexts.get('parent')!;+ root.tool_resources = { execute_code: { files: [file('retained', { bytes: 300_000 })] } };+ const preparation = {+ actor: h.host.session.actorFor('parent'),+ sessionKey: root.codeExecutionContext!.codeSessionKey,+ signal: h.signal,+ };+ try {+ await h.deps.prepareAgent({+ ...preparation,+ files: [file('old-publication', { bytes: 600_000 })],+ revision: 1,+ });+ await h.deps.prepareAgent({+ ...preparation,+ files: [file('new-publication', { bytes: 600_000 })],+ revision: 2,+ });+ expect(root.provisionState?.codeEnvFiles.map((entry) => entry.file_id)).toEqual([+ 'new-publication',+ ]);+ expect(root.tool_resources.execute_code?.files?.map((entry) => entry.file_id)).toEqual([+ 'retained',+ ]);+ } finally {+ await h.host.session.close();+ }+ });++ it('counts a current attachment also present in agent setup only once', async () => {+ const shared = file('same-file', { bytes: 600_000, context: FileContext.agents });+ const h = harness({ inputs: [shared], setup: [shared] });+ if (!h.req.config) throw new Error('Missing test configuration');+ h.req.config.fileConfig = { endpoints: { openAI: { totalSizeLimit: 1 } } };+ await h.prepare();+ await h.host.provision([Constants.EXECUTE_CODE], 'worker', h.signal, identity());+ expect(h.provisionToCodeEnv).toHaveBeenCalledTimes(1);+ });++ it('rechecks the managed deployment when an unchanged snapshot is reused', async () => {+ const h = harness();+ await h.prepare();+ h.contexts.get('worker')!.codeExecutionContext!.executionRouteKey = 'different-deployment';+ await expect(h.host.session.prepareTools('worker', identity(), h.signal)).rejects.toThrow(+ 'environment changed',+ );+ expect(h.provisionToCodeEnv).not.toHaveBeenCalled();+ });++ it('does not commit cancelled preparation and permits a new attempt', async () => {+ const h = harness();+ const entered = deferred<void>();+ const loaded = deferred<TFile[]>();+ h.loadFiles.mockImplementationOnce(async () => {+ entered.resolve();+ return loaded.promise;+ });+ const controller = new AbortController();+ const preparing = h.prepare(identity(), controller.signal);+ await entered.promise;+ controller.abort(new Error('cancel preparation'));+ loaded.resolve(h.setup);+ await expect(preparing).rejects.toThrow('cancel preparation');+ expect(h.host.getContext('worker', identity())).toBeUndefined();+ await h.prepare();+ expect(h.host.getContext('worker', identity())).toBeDefined();+ });++ it('rejects attached environments and preserves host deployment identity', async () => {+ const h = harness();+ const context = h.contexts.get('worker')!.codeExecutionContext!;+ const shared = {+ ...context,+ codeSessionKey: 'execution-session',+ runtimeSessionHint: 'execution-session',+ };+ expect(resolveRunFileCodeExecutionContext(context, shared)).toEqual(shared);+ expect(() =>+ resolveRunFileCodeExecutionContext({ ...context, executionRouteKey: 'other' }, shared),+ ).toThrow('environment changed');+ context.environmentType = 'attached';+ await expect(h.prepare()).rejects.toThrow('isolated managed');+ expect(h.loadFiles).not.toHaveBeenCalled();+ });+});diff --git a/packages/api/src/agents/files/host.ts b/packages/api/src/agents/files/host.tsnew file mode 100644index 0000000000..c0f187fc8e--- /dev/null+++ b/packages/api/src/agents/files/host.ts@@ -0,0 +1,511 @@+import { EToolResources, getCodeEnvRefs } from 'librechat-data-provider';+import type { CodeEnvFile, SubagentExecutionContext } from '@librechat/agents';+import type { Agent, TFile } from 'librechat-data-provider';+import type { ProvisionCallbackDeps, ProvisionToolContext } from '~/files/provision/callback';+import type { ToolEndCallback, ToolEndCallbackMetadata } from '~/agents/handlers';+import type { TFilterFilesByAgentAccess } from '~/agents/resources';+import type { RunFileSession, RunFileSessionDeps } from './session';+import type { CodeExecutionContext } from '~/agents/execution';+import type { ServerRequest } from '~/types';+import { isCodeArtifactToolOutput, isCodeFileToolName } from '~/agents/tools';+import { createProvisionFilesCallback } from '~/files/provision/callback';+import { assertModelBoundContent } from '~/middleware/modelBoundContent';+import { addFileToResource, primeResources } from '~/agents/resources';+import { filterFilesByEndpointRuntimeConfig } from '~/files/filter';+import { resolveResendToolResources } from '~/agents/initialize';+import { createRunFileSession } from './session';++export interface RunFileToolContext extends ProvisionToolContext {+ agent?: Agent;+ codeEnvAvailable?: boolean;+ codeExecutionContext?: CodeExecutionContext;+}++export interface RunFileHost<TContext extends RunFileToolContext = RunFileToolContext> {+ session: RunFileSession;+ getContext: (+ agentId: string,+ executionContext?: SubagentExecutionContext,+ ) => TContext | undefined;+ provision: (+ toolNames: string[],+ agentId: string,+ signal: AbortSignal,+ executionContext?: SubagentExecutionContext,+ ) => Promise<CodeEnvFile[] | undefined>;+ /** Used immediately after the handler has authorized the current tool batch. */+ provisionPrepared: (+ toolNames: string[],+ agentId: string,+ signal: AbortSignal,+ executionContext?: SubagentExecutionContext,+ ) => Promise<CodeEnvFile[] | undefined>;+ deliverToolEnd: (+ callback: ToolEndCallback,+ data: Parameters<ToolEndCallback>[0],+ metadata: ToolEndCallbackMetadata,+ ) => Promise<void>;+}++/** Overrides only the session identity; deployments and credentials remain host-resolved. */+export function resolveRunFileCodeExecutionContext(+ resolved: CodeExecutionContext,+ shared?: CodeExecutionContext,+): CodeExecutionContext {+ if (shared == null) return resolved;+ if (+ resolved.baseUrl !== shared.baseUrl ||+ resolved.executionProfile !== shared.executionProfile ||+ resolved.executionRouteKey !== shared.executionRouteKey ||+ resolved.environmentId !== shared.environmentId ||+ resolved.bridgeWorkerId !== shared.bridgeWorkerId ||+ resolved.environmentType === 'attached'+ ) {+ throw new Error('The shared-file execution environment changed during this run.');+ }+ return {+ ...resolved,+ codeSessionKey: shared.codeSessionKey,+ runtimeSessionHint: shared.runtimeSessionHint,+ };+}++export function createRunFileHost<TContext extends RunFileToolContext>({+ req,+ contexts,+ createdAt,+ inputFileIds,+ getInputs,+ loadFiles,+ filterFiles,+ validateMessages,+ encodeMessages,+ listPublications,+ snapshots,+ publish,+ emit,+ audit,+ provisioning,+}: {+ req: ServerRequest;+ contexts: Map<string, TContext>;+ createdAt: number;+ inputFileIds: ReadonlySet<string>;+ getInputs: () => readonly TFile[];+ loadFiles: (fileIds: string[]) => Promise<TFile[]>;+ filterFiles: TFilterFilesByAgentAccess;+ validateMessages: RunFileSessionDeps['validateMessages'];+ encodeMessages: RunFileSessionDeps['encodeMessages'];+ listPublications: RunFileSessionDeps['listPublications'];+ snapshots: RunFileSessionDeps['snapshots'];+ publish: RunFileSessionDeps['publish'];+ emit: RunFileSessionDeps['emit'];+ audit?: RunFileSessionDeps['audit'];+ provisioning: Pick<+ ProvisionCallbackDeps,+ | 'provisionToCodeEnv'+ | 'provisionToVectorDB'+ | 'updateFile'+ | 'updateCodeEnvRef'+ | 'addEmbeddedEntity'+ >;+}): RunFileHost<TContext> {+ const user = req.user;+ if (user == null) throw new Error('Run file sharing requires an authenticated user.');+ const executionContexts = new Map<string, TContext>();+ const prepared = new Map<+ string,+ {+ revision: number;+ signature: string;+ files: Map<string, TFile>;+ setupFiles: Map<string, TFile>;+ loadedSetupIds: Set<string>;+ }+ >();+ const provisioningCallbacks = new Map<string, ReturnType<typeof createProvisionFilesCallback>>();+ const operations = new Map<string, Promise<unknown>>();++ /** Priming and tool provisioning both mutate these queues. Other executions, even of+ * the same configured agent, have independent queues and can make progress together. */+ function serialize<T>(key: string, signal: AbortSignal, operation: () => Promise<T>): Promise<T> {+ const previous = operations.get(key) ?? Promise.resolve();+ const current = previous+ .catch(() => undefined)+ .then(() => {+ signal.throwIfAborted();+ return operation();+ });+ operations.set(key, current);+ const release = () => {+ if (operations.get(key) === current) operations.delete(key);+ };+ void current.then(release, release);+ return current;+ }++ function retainContext(key: string, agentId: string, context: TContext): void {+ executionContexts.set(key, context);+ if (!provisioningCallbacks.has(key)) {+ provisioningCallbacks.set(+ key,+ createProvisionFilesCallback({+ req,+ agentToolContexts: new Map([[agentId, context]]),+ ...provisioning,+ }),+ );+ }+ }+ const session = createRunFileSession({+ policy: req.config?.endpoints?.agents?.fileSharing,+ userId: user.id,+ tenantId: user.tenantId,+ createdAt,+ inputFileIds,+ getInputs,+ getAgent: (agentId) => contexts.get(agentId)?.agent,+ listPublications,+ snapshots,+ publish,+ emit,+ audit,+ validateMessages,+ encodeMessages,+ prepareAgent: async ({ actor, files, revision, sessionKey, signal }) => {+ const key = JSON.stringify(actor);+ await serialize(key, signal, async () => {+ const previous = prepared.get(key);+ // Snapshots are numbered before their asynchronous reads. A late older read+ // cannot restore a removed grant or replace a newer actor's queues.+ if (previous != null && revision <= previous.revision) return;+ const source = contexts.get(actor.agentId);+ if (!source?.agent) throw new Error('The shared-file agent is no longer available.');+ const isRoot = actor.executionId === session.actorFor(actor.agentId).executionId;+ if (!isRoot && source.codeExecutionContext?.environmentType === 'attached') {+ throw new Error('Run file sharing requires an isolated managed code environment.');+ }+ const screen = (candidates: TFile[], consumedBytes = 0): TFile[] => {+ const admitted = filterFilesByEndpointRuntimeConfig(req.config, {+ files: candidates,+ endpoint: source.agent!.endpoint ?? source.agent!.provider ?? 'agents',+ preserveTextSources: true,+ consumedBytes,+ });+ if (admitted.length !== candidates.length) {+ throw new Error('A shared file is not supported by the receiving agent.');+ }+ assertModelBoundContent({ filters: req.config?.filters, files: admitted });+ return admitted;+ };+ const signature = JSON.stringify(files.map((file) => file.file_id).sort());+ const existingContext = executionContexts.get(key);+ if (isRoot) {+ // The root already passed normal conversation authorization and priming.+ // Sharing only limits what descendants inherit; its own historical files,+ // pending uploads and runtime session must survive activation and refresh.+ const context = existingContext ?? source;+ const existingFiles = new Map(+ [+ ...Object.values(context.tool_resources ?? {}).flatMap(+ (resource) => resource?.files ?? [],+ ),+ ...(context.provisionState?.codeEnvFiles ?? []),+ ...(context.provisionState?.vectorDBFiles ?? []),+ ...(previous?.files.values() ?? []),+ ].map((file) => [file.file_id, file]),+ );+ const currentIds = new Set(files.map((file) => file.file_id));+ let consumedBytes = 0;+ for (const file of existingFiles.values()) {+ if (!currentIds.has(file.file_id) && !previous?.files.has(file.file_id)) {+ consumedBytes += file.bytes;+ }+ }+ screen(files, consumedBytes);+ if (previous?.signature === signature) {+ previous.revision = revision;+ return;+ }+ const currentFiles = files.map(+ (file) => existingFiles.get(file.file_id) ?? structuredClone(file),+ );+ const removed = new Set(+ [...(previous?.files.keys() ?? [])].filter((id) => !currentIds.has(id)),+ );+ const added = currentFiles.filter((file) => !existingFiles.has(file.file_id));+ const primed = await primeResources({+ req,+ appConfig: req.config,+ agentId: actor.agentId,+ attachments: Promise.resolve(added),+ requestFileSet: new Set(added.map((file) => file.file_id)),+ tool_resources: undefined,+ getFiles: async () => [],+ enabledToolResources: resolveResendToolResources({+ tools: source.agent.tools ?? [],+ codeEnvAvailable: source.codeEnvAvailable === true,+ }),+ codeRouteKey:+ context.codeExecutionContext?.executionRouteKey ??+ context.codeExecutionContext?.executionProfile,+ codeBaseUrl: context.codeExecutionContext?.baseUrl,+ });+ signal.throwIfAborted();+ const resources = context.tool_resources ?? {};+ for (const resource of Object.values(resources)) {+ if (resource?.files)+ resource.files = resource.files.filter((file: TFile) => !removed.has(file.file_id));+ if (resource?.file_ids)+ resource.file_ids = resource.file_ids.filter((id: string) => !removed.has(id));+ }+ const processedResourceFiles = new Set<string>();+ for (const [type, resource] of Object.entries(primed.tool_resources ?? {})) {+ for (const file of resource?.files ?? [])+ addFileToResource({+ file,+ resourceType: type as EToolResources,+ tool_resources: resources,+ processedResourceFiles,+ });+ }+ context.tool_resources = resources;+ const state = context.provisionState ?? primed.provisionState;+ if (state) {+ const merge = (existing: TFile[], incoming: TFile[]) => [+ ...new Map(+ [...existing.filter((file) => !removed.has(file.file_id)), ...incoming].map(+ (file) => [file.file_id, file],+ ),+ ).values(),+ ];+ state.codeEnvFiles = merge(+ state.codeEnvFiles,+ primed.provisionState?.codeEnvFiles ?? [],+ );+ state.vectorDBFiles = merge(+ state.vectorDBFiles,+ primed.provisionState?.vectorDBFiles ?? [],+ );+ context.provisionState = state;+ }+ const removedCodeIds = new Set(+ [...removed].flatMap((id) =>+ getCodeEnvRefs(previous?.files.get(id)?.metadata).map(([, ref]) => ref.file_id),+ ),+ );+ context.pendingProvisionedCodeFiles = context.pendingProvisionedCodeFiles?.filter(+ (file) => !removedCodeIds.has(file.id),+ );+ retainContext(key, actor.agentId, context);+ prepared.set(key, {+ revision,+ signature,+ files: new Map(currentFiles.map((file) => [file.file_id, file])),+ setupFiles: new Map(),+ loadedSetupIds: new Set(),+ });+ return;+ }+ screen(files);+ const codeExecutionContext =+ source.codeExecutionContext == null+ ? undefined+ : resolveRunFileCodeExecutionContext(source.codeExecutionContext, {+ ...source.codeExecutionContext,+ codeSessionKey: sessionKey,+ runtimeSessionHint: sessionKey,+ });+ if (codeExecutionContext && existingContext?.codeExecutionContext) {+ resolveRunFileCodeExecutionContext(+ codeExecutionContext,+ existingContext.codeExecutionContext,+ );+ }+ if (previous?.signature === signature) {+ previous.revision = revision;+ return;+ }+ // Unified input records are immutable for this run. Keep this actor's local+ // provisioning results, which may be newer than a manifest or database read.+ const currentFiles = files.map(+ (file) => previous?.files.get(file.file_id) ?? structuredClone(file),+ );+ const setupFiles = previous?.setupFiles ?? new Map<string, TFile>();+ const loadedSetupIds = previous?.loadedSetupIds ?? new Set<string>();+ const admittedSetupIds = new Set<string>();+ let failed: { error: unknown } | undefined;+ const primed = await primeResources({+ req,+ appConfig: req.config,+ agentId: actor.agentId,+ attachments: Promise.resolve(currentFiles),+ requestFileSet: new Set(currentFiles.map((file) => file.file_id)),+ tool_resources: source.agent.tool_resources,+ enabledToolResources: resolveResendToolResources({+ tools: source.agent.tools ?? [],+ codeEnvAvailable: source.codeEnvAvailable === true,+ }),+ getFiles: async (filter) => {+ try {+ const ids = (filter as { file_id: { $in: string[] } }).file_id.$in;+ const missing = ids.filter((id) => !loadedSetupIds.has(id));+ if (missing.length > 0) {+ const loaded = await loadFiles(missing);+ const requested = new Set(missing);+ for (const file of loaded) {+ if (requested.has(file.file_id))+ setupFiles.set(file.file_id, structuredClone(file));+ }+ for (const id of missing) loadedSetupIds.add(id);+ }+ return ids.flatMap((id) => {+ const file = setupFiles.get(id);+ return file ? [file] : [];+ });+ } catch (error) {+ failed = { error };+ throw error;+ }+ },+ filterFiles: async (params) => {+ try {+ return await filterFiles(params);+ } catch (error) {+ failed = { error };+ throw error;+ }+ },+ codeRouteKey:+ codeExecutionContext?.executionRouteKey ?? codeExecutionContext?.executionProfile,+ codeBaseUrl: codeExecutionContext?.baseUrl,+ screenPersistentFiles: (candidates) => {+ try {+ const candidateIds = new Set(candidates.map((file) => file.file_id));+ const consumedBytes = currentFiles.reduce(+ (total, file) => total + (candidateIds.has(file.file_id) ? 0 : file.bytes),+ 0,+ );+ const admitted = screen(candidates, consumedBytes);+ for (const file of admitted) admittedSetupIds.add(file.file_id);+ return admitted;+ } catch (error) {+ failed = { error };+ throw error;+ }+ },+ });+ // primeResources supports a best-effort legacy caller. A shared-file host+ // must fail closed when its authorized resource load or policy check fails.+ if (failed) throw failed.error;+ signal.throwIfAborted();+ const admittedIds = new Set([+ ...currentFiles.map((file) => file.file_id),+ ...admittedSetupIds,+ ]);+ for (const resource of Object.values(primed.tool_resources ?? {})) {+ if (resource?.file_ids) {+ resource.file_ids = resource.file_ids.filter((id: string) => admittedIds.has(id));+ }+ }+ const provisionState =+ primed.provisionState ??+ (existingContext?.provisionState+ ? {+ ...existingContext.provisionState,+ codeEnvFiles: [],+ vectorDBFiles: [],+ codeEnvRecoveryNames: undefined,+ }+ : undefined);+ if (provisionState) provisionState.agentScopedFileIds = admittedSetupIds;+ const context: TContext = existingContext ?? {+ ...source,+ pendingProvisionedCodeFiles: undefined,+ };+ context.tool_resources = primed.tool_resources;+ context.provisionState = provisionState;+ context.codeExecutionContext = codeExecutionContext;+ if (context.pendingProvisionedCodeFiles) {+ const currentCodeIds = new Set(+ [+ ...currentFiles,+ ...[...admittedSetupIds].flatMap((id) => setupFiles.get(id) ?? []),+ ].flatMap((file) => getCodeEnvRefs(file.metadata).map(([, ref]) => ref.file_id)),+ );+ context.pendingProvisionedCodeFiles = context.pendingProvisionedCodeFiles.filter((file) =>+ currentCodeIds.has(file.id),+ );+ }+ retainContext(key, actor.agentId, context);+ prepared.set(key, {+ revision,+ signature,+ files: new Map(currentFiles.map((file) => [file.file_id, file])),+ setupFiles,+ loadedSetupIds,+ });+ });+ },+ });++ function getContext(+ agentId: string,+ executionContext?: SubagentExecutionContext,+ ): TContext | undefined {+ if (!session.isActive()) return contexts.get(agentId);+ return executionContexts.get(JSON.stringify(session.actorFor(agentId, executionContext)));+ }++ async function provision(+ toolNames: string[],+ agentId: string,+ signal: AbortSignal,+ executionContext?: SubagentExecutionContext,+ ) {+ if (!session.isActive()) return undefined;+ await session.prepareTools(agentId, executionContext, signal);+ return provisionPrepared(toolNames, agentId, signal, executionContext);+ }++ async function provisionPrepared(+ toolNames: string[],+ agentId: string,+ signal: AbortSignal,+ executionContext?: SubagentExecutionContext,+ ): Promise<CodeEnvFile[] | undefined> {+ if (!session.isActive()) return undefined;+ const key = JSON.stringify(session.actorFor(agentId, executionContext));+ if (!prepared.has(key)) throw new Error('The shared-file execution has not been prepared.');+ return serialize(key, signal, async () =>+ provisioningCallbacks.get(key)?.(toolNames, agentId, signal),+ );+ }++ const deliverToolEnd = async (+ callback: ToolEndCallback,+ data: Parameters<ToolEndCallback>[0],+ metadata: ToolEndCallbackMetadata,+ ): Promise<void> => {+ const executionContext = metadata.executionContext as SubagentExecutionContext | undefined;+ if (!session.isActive() || executionContext == null) return callback(data, metadata);+ if (!isCodeArtifactToolOutput(data.output) && !isCodeFileToolName(data.output.name)) {+ return callback(data, metadata);+ }+ const agentId = metadata.executingAgentId ?? metadata.agentId ?? metadata.agent_id;+ if (typeof agentId !== 'string')+ throw new Error('The shared-file producer has no agent identity.');+ const context = getContext(agentId, executionContext);+ if (!context) throw new Error('The shared-file producer has no execution context.');+ if (data.output.artifact == null || typeof data.output.artifact !== 'object') return;+ await session.capture(+ agentId,+ executionContext,+ data.output.tool_call_id,+ data.output.artifact as Parameters<typeof session.capture>[3],+ context.codeExecutionContext,+ );+ };++ return { session, getContext, provision, provisionPrepared, deliverToolEnd };+}diff --git a/packages/api/src/agents/files/index.ts b/packages/api/src/agents/files/index.tsnew file mode 100644index 0000000000..9293cd7f4e--- /dev/null+++ b/packages/api/src/agents/files/index.ts@@ -0,0 +1,5 @@+export * from './manifest';+export * from './session';+export * from './host';+export * from './binding';+export * from './encode';diff --git a/packages/api/src/agents/files/manifest.spec.ts b/packages/api/src/agents/files/manifest.spec.tsnew file mode 100644index 0000000000..4619641ef5--- /dev/null+++ b/packages/api/src/agents/files/manifest.spec.ts@@ -0,0 +1,380 @@+import { FileContext, FileSources } from 'librechat-data-provider';+import type { TFile } from 'librechat-data-provider';+import type { RunArtifact, RunFileScope, RunFileStore } from './manifest';+import { createRunFileManifest } from './manifest';++const scope: RunFileScope = {+ userId: 'user',+ tenantId: 'tenant',+ conversationId: 'conversation',+ runId: 'run',+};+const parent = { executionId: 'parent', agentId: 'lead' };+const child = { executionId: 'child', agentId: 'worker' };+const sibling = { executionId: 'sibling', agentId: 'reviewer' };+const input: TFile = {+ file_id: 'input',+ filename: 'input.pdf',+ type: 'application/pdf',+ user: 'user',+ tenantId: 'tenant',+ bytes: 12,+ embedded: false,+ filepath: '/private/input.pdf',+ object: 'file',+ usage: 0,+ source: FileSources.local,+ llmDeliveryPath: 'none',+ metadata: { destinationChosen: false },+};++function setup(+ options: { allowSiblingSharing?: boolean; maxFiles?: number; files?: TFile[] } = {},+) {+ let time = 0;+ let fail = false;+ let writes = 0;+ const saved: TFile[] = [];+ const store: RunFileStore<RunArtifact> = {+ list: async () => structuredClone(saved),+ publish: async ({ artifact, provenance }) => {+ writes++;+ if (fail) throw new Error('Storage unavailable');+ const file: TFile = {+ ...input,+ file_id: `${provenance.executionId}-${artifact.id}`,+ filename: artifact.filename,+ conversationId: scope.conversationId,+ context: FileContext.run_artifact,+ metadata: { runFile: provenance },+ };+ saved.push(file);+ return structuredClone(file);+ },+ };+ const create = () =>+ createRunFileManifest({+ scope,+ policy: {+ allowSiblingSharing: options.allowSiblingSharing ?? false,+ maxFiles: options.maxFiles ?? 20,+ ttlMs: 1000,+ },+ root: {+ id: parent.executionId,+ agentIds: ['lead'],+ allowedAgentIds: ['worker', 'reviewer', 'lead'],+ },+ inputFiles: options.files ?? [input],+ inputFileIds: new Set(['input']),+ createdAt: 0,+ now: () => time,+ store,+ });+ const manifest = create();+ const register = (target: ReturnType<typeof create>) => {+ target.register({+ id: 'child',+ parentId: 'parent',+ parentAgentId: 'lead',+ agentIds: ['worker'],+ allowedAgentIds: ['nested'],+ });+ target.register({+ id: 'sibling',+ parentId: 'parent',+ parentAgentId: 'lead',+ agentIds: ['reviewer'],+ allowedAgentIds: [],+ });+ };+ register(manifest);+ return {+ manifest,+ saved,+ store,+ create,+ register,+ writes: () => writes,+ fail: (value: boolean) => {+ fail = value;+ },+ time: (value: number) => {+ time = value;+ },+ };+}++describe('run file manifest', () => {+ it('seeds only authorized current-turn inputs and returns copies without storage paths in the catalog', async () => {+ const { manifest } = setup({+ files: [+ input,+ { ...input, file_id: 'historical' },+ { ...input, file_id: 'setup', context: FileContext.agents },+ { ...input, tenantId: 'foreign', filename: 'foreign.pdf' },+ ],+ });+ const files = await manifest.getFiles(child);+ expect(files.map((file) => file.file_id)).toEqual(['input']);+ files[0].metadata = { destinationChosen: true };+ const catalog = await manifest.list(child);+ expect(catalog[0].paths).toEqual(['execute_code', 'file_search']);+ expect(catalog[0]).not.toHaveProperty('filepath');+ expect(catalog[0].provenance).toEqual({ kind: 'user_attachment', runId: 'run' });+ });++ it('rejects unregistered actors, unapproved descendants and identity reassignment', async () => {+ const { manifest } = setup();+ await expect(manifest.list({ ...child, agentId: 'lead' })).rejects.toThrow('cannot access');+ await manifest.getFiles(child, undefined, 'snapshot');+ await expect(+ manifest.getFiles({ ...child, agentId: 'lead' }, undefined, 'snapshot'),+ ).rejects.toThrow('cannot access');+ expect(() =>+ manifest.register({+ id: 'stranger',+ parentId: 'child',+ parentAgentId: 'worker',+ agentIds: ['reviewer'],+ allowedAgentIds: [],+ }),+ ).toThrow('not authorized');+ expect(() =>+ manifest.register({+ id: 'child',+ parentId: 'parent',+ parentAgentId: 'lead',+ agentIds: ['reviewer'],+ allowedAgentIds: [],+ }),+ ).toThrow('cannot be reassigned');+ });++ it('keeps generated outputs private until publication and permits only the producing execution to publish', async () => {+ const { manifest, writes } = setup();+ manifest.stage(child, { id: 'csv', filename: 'report.csv' });+ expect((await manifest.list(parent)).map((file) => file.file_id)).toEqual(['input']);+ expect(writes()).toBe(0);+ await expect(manifest.publish(sibling, 'csv')).rejects.toThrow('Only artifacts');+ const file = await manifest.publish(child, 'csv');+ expect((await manifest.list(parent)).map((entry) => entry.file_id)).toContain(file.file_id);+ expect((await manifest.list(sibling)).map((entry) => entry.file_id)).toEqual(['input']);+ expect(file.metadata?.runFile).toMatchObject({+ agentId: 'worker',+ executionId: 'child',+ parentExecutionId: 'parent',+ inputFileIds: ['input'],+ });+ });++ it('does not confuse concurrent self-spawns with the parent or each other', async () => {+ const { manifest } = setup();+ manifest.register({+ id: 'self-a',+ parentId: 'parent',+ parentAgentId: 'lead',+ agentIds: ['lead'],+ allowedAgentIds: [],+ });+ manifest.register({+ id: 'self-b',+ parentId: 'parent',+ parentAgentId: 'lead',+ agentIds: ['lead'],+ allowedAgentIds: [],+ });+ const a = { executionId: 'self-a', agentId: 'lead' };+ const b = { executionId: 'self-b', agentId: 'lead' };+ manifest.stage(a, { id: 'csv', filename: 'report.csv' });+ const file = await manifest.publish(a, 'csv');+ expect((await manifest.list(b)).map((entry) => entry.file_id)).not.toContain(file.file_id);+ await expect(manifest.publish(b, 'csv')).rejects.toThrow('Only artifacts');+ });++ it('requires both deployment permission and explicit recipients for sibling sharing', async () => {+ const disabled = setup().manifest;+ disabled.stage(child, { id: 'csv', filename: 'report.csv' });+ await expect(disabled.publish(child, 'csv', ['reviewer'])).rejects.toThrow('sharing policy');+ const { manifest } = setup({ allowSiblingSharing: true });+ manifest.stage(child, { id: 'csv', filename: 'report.csv' });+ await expect(manifest.publish(child, 'csv', ['unknown'])).rejects.toThrow('sharing policy');+ const file = await manifest.publish(child, 'csv', ['reviewer', 'nested']);+ expect((await manifest.list(sibling)).map((entry) => entry.file_id)).toContain(file.file_id);+ manifest.register({+ id: 'nested-execution',+ parentId: 'child',+ parentAgentId: 'worker',+ agentIds: ['nested'],+ allowedAgentIds: [],+ });+ expect(+ (await manifest.list({ executionId: 'nested-execution', agentId: 'nested' })).map(+ (entry) => entry.file_id,+ ),+ ).toContain(file.file_id);+ });++ it('deduplicates concurrent publication, retries storage errors, and preserves recipients', async () => {+ const { manifest, writes, fail } = setup({ allowSiblingSharing: true });+ manifest.stage(child, { id: 'csv', filename: 'report.csv' });+ fail(true);+ await expect(manifest.publish(child, 'csv')).rejects.toThrow('Storage unavailable');+ fail(false);+ const files = await Promise.all([+ manifest.publish(child, 'csv'),+ manifest.publish(child, 'csv'),+ ]);+ expect(files[0].file_id).toBe(files[1].file_id);+ expect(writes()).toBe(2);+ await expect(manifest.publish(child, 'csv', ['reviewer'])).rejects.toThrow(+ 'different recipients',+ );+ });++ it('restores scoped publications without private outputs and keeps other runs out', async () => {+ const { manifest, saved, create, register, writes } = setup();+ manifest.stage(child, { id: 'csv', filename: 'report.csv' });+ const published = await manifest.publish(child, 'csv');+ saved.push({+ ...published,+ file_id: 'other-run',+ metadata: { runFile: { ...published.metadata!.runFile!, runId: 'different-run' } },+ });+ saved.push({ ...published, file_id: 'other-tenant', tenantId: 'other' });+ const resumed = create();+ register(resumed);+ expect((await resumed.list(parent)).map((file) => file.file_id)).toEqual([+ 'input',+ published.file_id,+ ]);+ expect((await resumed.publish(child, 'csv')).file_id).toBe(published.file_id);+ expect(writes()).toBe(1);+ });++ it('loads a snapshot once and includes local publications without another storage read', async () => {+ const { manifest, create, register, store } = setup();+ manifest.stage(child, { id: 'saved', filename: 'saved.csv' });+ const saved = await manifest.publish(child, 'saved');+ const read = jest.spyOn(store, 'list');+ const resumed = create();+ register(resumed);++ const initial = await resumed.getFiles(parent, undefined, 'snapshot');+ expect(initial.map((file) => file.file_id)).toEqual(['input', saved.file_id]);+ initial[0].filename = 'changed.csv';+ expect((await resumed.getFiles(parent, undefined, 'snapshot'))[0].filename).toBe(+ input.filename,+ );+ expect(read).toHaveBeenCalledTimes(1);++ resumed.stage(child, { id: 'new', filename: 'new.csv' });+ const published = await resumed.publish(child, 'new');+ const reads = read.mock.calls.length;+ expect(+ (await resumed.getFiles(parent, undefined, 'snapshot')).map((file) => file.file_id),+ ).toEqual(['input', saved.file_id, published.file_id]);+ expect(+ (await resumed.getFiles(sibling, undefined, 'snapshot')).map((file) => file.file_id),+ ).toEqual(['input']);+ expect(read).toHaveBeenCalledTimes(reads);+ });++ it('retries snapshot reads after initial or later storage failures', async () => {+ const { manifest, store } = setup();+ const read = jest.spyOn(store, 'list').mockRejectedValueOnce(new Error('Storage unavailable'));+ await expect(manifest.getFiles(parent, undefined, 'snapshot')).rejects.toThrow(+ 'Storage unavailable',+ );+ await expect(manifest.getFiles(parent, undefined, 'snapshot')).resolves.toEqual([input]);+ await expect(manifest.getFiles(parent, undefined, 'snapshot')).resolves.toEqual([input]);+ expect(read).toHaveBeenCalledTimes(2);++ read.mockRejectedValueOnce(new Error('Storage unavailable'));+ await expect(manifest.getFiles(parent)).rejects.toThrow('Storage unavailable');+ await expect(manifest.getFiles(parent, undefined, 'snapshot')).resolves.toEqual([input]);+ await expect(manifest.getFiles(parent, undefined, 'snapshot')).resolves.toEqual([input]);+ expect(read).toHaveBeenCalledTimes(4);+ });++ it.each(['refresh', 'snapshot'] as const)(+ 'expires or cancels %s access without deleting durable user files',+ async (mode) => {+ const { manifest, saved, time } = setup();+ manifest.stage(child, { id: 'csv', filename: 'report.csv' });+ await manifest.publish(child, 'csv');+ await expect(manifest.getFiles(parent, AbortSignal.abort(), mode)).rejects.toThrow();+ time(1000);+ await expect(manifest.getFiles(parent, undefined, mode)).rejects.toThrow('expired');+ expect(saved).toHaveLength(1);+ expect(() => manifest.stage(child, { id: 'new', filename: 'new.csv' })).toThrow('expired');+ },+ );++ it.each(['refresh', 'snapshot'] as const)(+ 'coalesces a simultaneous %s read without sharing cancellation between children',+ async (mode) => {+ const { manifest, store } = setup();+ await manifest.getFiles(parent);+ let finishRead!: (files: TFile[]) => void;+ const read = jest.spyOn(store, 'list').mockImplementation(+ () =>+ new Promise<TFile[]>((resolve) => {+ finishRead = resolve;+ }),+ );+ const abort = new AbortController();+ const cancelled = manifest.list(child, abort.signal);+ const other = manifest.getFiles(sibling, undefined, mode);+ expect(read).toHaveBeenCalledTimes(1);+ abort.abort();+ finishRead([]);+ await expect(cancelled).rejects.toThrow();+ await expect(other).resolves.toEqual([expect.objectContaining({ file_id: 'input' })]);+ },+ );++ it('does not discard a publication when an older in-flight read finishes after the commit', async () => {+ const { manifest, store } = setup();+ manifest.stage(child, { id: 'csv', filename: 'report.csv' });+ let finishWrite!: () => void;+ const persist = store.publish;+ const writeStarted = new Promise<void>((resolve) => {+ store.publish = async (params) => {+ resolve();+ await new Promise<void>((finish) => {+ finishWrite = finish;+ });+ return persist(params);+ };+ });+ const publication = manifest.publish(child, 'csv');+ await writeStarted;+ let finishRead!: (files: TFile[]) => void;+ jest.spyOn(store, 'list').mockImplementationOnce(+ () =>+ new Promise<TFile[]>((resolve) => {+ finishRead = resolve;+ }),+ );+ const reading = manifest.list(parent);+ finishWrite();+ const published = await publication;+ finishRead([]);+ await expect(reading).resolves.toContainEqual(+ expect.objectContaining({ file_id: published.file_id }),+ );+ });++ it('drops deleted publications on the next read and enforces configured capacity', async () => {+ const { manifest, saved } = setup({ maxFiles: 2 });+ manifest.stage(child, { id: 'csv', filename: 'report.csv' });+ const published = await manifest.publish(child, 'csv');+ expect(() => manifest.stage(child, { id: 'second', filename: 'second.csv' })).toThrow('limit');+ saved.splice(0);+ expect((await manifest.list(parent)).map((file) => file.file_id)).not.toContain(+ published.file_id,+ );+ await expect(manifest.publish(child, 'csv')).rejects.toThrow('Only artifacts');+ });+});diff --git a/packages/api/src/agents/files/manifest.ts b/packages/api/src/agents/files/manifest.tsnew file mode 100644index 0000000000..66cb96d83a--- /dev/null+++ b/packages/api/src/agents/files/manifest.ts@@ -0,0 +1,430 @@+import { canToolResourceConsume, EToolResources, FileSources } from 'librechat-data-provider';+import type { RunFileProvenance, TFile } from 'librechat-data-provider';++export interface RunFileScope {+ userId: string;+ tenantId?: string;+ conversationId: string;+ runId: string;+}++export interface RunFilePolicy {+ allowSiblingSharing: boolean;+ maxFiles: number;+ ttlMs: number;+}++export interface RunFileExecution {+ id: string;+ parentId?: string;+ parentAgentId?: string;+ agentIds: readonly string[];+ allowedAgentIds: readonly string[];+}++export interface RunFileActor {+ executionId: string;+ agentId: string;+}++export interface RunArtifact {+ id: string;+ filename: string;+}++export interface RunFileEntry {+ file_id: string;+ filename: string;+ type: string;+ source?: FileSources;+ llmDeliveryPath?: TFile['llmDeliveryPath'];+ paths: Array<'provider' | 'text' | EToolResources.execute_code | EToolResources.file_search>;+ provenance: RunFileProvenance | { kind: 'user_attachment'; runId: string };+}++/** Describes an already authorized snapshot without another storage read. */+export function describeRunFiles(files: readonly TFile[], runId: string): RunFileEntry[] {+ return files.map((file) => {+ const paths: RunFileEntry['paths'] = [];+ if (file.llmDeliveryPath === 'provider') paths.push('provider');+ if (file.llmDeliveryPath === 'text' || file.source === FileSources.text) paths.push('text');+ const chosen = file.metadata?.destinationChosen !== false;+ if (file.source !== FileSources.text) {+ if (+ canToolResourceConsume(EToolResources.execute_code, file.type) &&+ (!chosen || file.metadata?.codeEnvRef != null || file.metadata?.codeEnvRefs != null)+ )+ paths.push(EToolResources.execute_code);+ if (+ canToolResourceConsume(EToolResources.file_search, file.type) &&+ (!chosen || file.embedded)+ )+ paths.push(EToolResources.file_search);+ }+ return {+ file_id: file.file_id,+ filename: file.filename,+ type: file.type,+ source: file.source,+ llmDeliveryPath: file.llmDeliveryPath,+ paths,+ provenance: file.metadata?.runFile ?? { kind: 'user_attachment', runId },+ };+ });+}++export interface RunFileStore<TArtifact extends RunArtifact> {+ list: (scope: RunFileScope) => Promise<TFile[]>;+ publish: (params: {+ scope: RunFileScope;+ artifact: TArtifact;+ provenance: RunFileProvenance;+ signal?: AbortSignal;+ }) => Promise<TFile>;+}++export interface RunFileAudit {+ action: 'inherit' | 'publish' | 'expire' | 'cleanup_failed';+ scope: RunFileScope;+ executionId: string;+ agentId?: string;+ fileIds: string[];+ recipientAgentIds?: string[];+}++export type RunFileReadMode = 'refresh' | 'snapshot';++export interface RunFileManifest<TArtifact extends RunArtifact = RunArtifact> {+ register: (execution: RunFileExecution) => void;+ getFiles: (actor: RunFileActor, signal?: AbortSignal, mode?: RunFileReadMode) => Promise<TFile[]>;+ list: (actor: RunFileActor, signal?: AbortSignal) => Promise<RunFileEntry[]>;+ stage: (actor: RunFileActor, artifact: TArtifact) => void;+ discardArtifacts: (actor: RunFileActor) => void;+ publish: (+ actor: RunFileActor,+ artifactId: string,+ recipientAgentIds?: string[],+ signal?: AbortSignal,+ ) => Promise<TFile>;+ close: () => void;+}++/** Metadata and grants are run-local; canonical file bytes remain in the unified file store. */+export function createRunFileManifest<TArtifact extends RunArtifact>({+ scope,+ policy,+ root,+ inputFiles,+ inputFileIds,+ createdAt,+ store,+ now = Date.now,+ audit = () => undefined,+}: {+ scope: RunFileScope;+ policy: RunFilePolicy;+ root: RunFileExecution;+ inputFiles: readonly TFile[];+ inputFileIds: ReadonlySet<string>;+ createdAt: number;+ store: RunFileStore<TArtifact>;+ now?: () => number;+ audit?: (event: RunFileAudit) => void;+}): RunFileManifest<TArtifact> {+ if (!scope.userId || !scope.conversationId || !scope.runId || root.parentId != null) {+ throw new Error('Invalid shared-file run identity.');+ }+ if (!Number.isFinite(createdAt) || policy.maxFiles < 1 || policy.ttlMs < 1) {+ throw new Error('Invalid shared-file run policy.');+ }++ const executions = new Map<string, RunFileExecution>();+ const files = new Map<string, TFile>();+ const inputs = new Set<string>();+ const artifacts = new Map<string, { actor: RunFileActor; artifact: TArtifact }>();+ const publications = new Map<string, Promise<TFile>>();+ let closed = false;+ let pendingPublications = 0;+ let publicationRevision = 0;+ let pendingRefresh: Promise<void> | undefined;+ let hasLoadedPublications = false;+ executions.set(root.id, structuredClone(root));++ function owns(file: TFile): boolean {+ return file.user === scope.userId && (file.tenantId ?? '') === (scope.tenantId ?? '');+ }++ for (const file of inputFiles) {+ if (!inputFileIds.has(file.file_id) || !owns(file) || inputs.has(file.file_id)) {+ continue;+ }+ inputs.add(file.file_id);+ files.set(file.file_id, structuredClone(file));+ }+ if (files.size > policy.maxFiles) {+ throw new Error('The shared-file manifest exceeds the configured file limit.');+ }++ function close(): void {+ if (closed) return;+ closed = true;+ artifacts.clear();+ files.clear();+ executions.clear();+ publications.clear();+ audit({ action: 'expire', scope, executionId: root.id, fileIds: [] });+ }++ function assertActive(signal?: AbortSignal): void {+ signal?.throwIfAborted();+ if (now() >= createdAt + policy.ttlMs) close();+ if (closed) throw new Error('This shared-file run has expired. Attach the file to a new turn.');+ }++ function executionFor(actor: RunFileActor, signal?: AbortSignal): RunFileExecution {+ assertActive(signal);+ const execution = executions.get(actor.executionId);+ if (!execution?.agentIds.includes(actor.agentId)) {+ throw new Error('This agent execution cannot access the shared-file run.');+ }+ return execution;+ }++ function register(execution: RunFileExecution): void {+ assertActive();+ const parent = execution.parentId == null ? undefined : executions.get(execution.parentId);+ if (+ !execution.id ||+ !parent ||+ !execution.parentAgentId ||+ !parent.agentIds.includes(execution.parentAgentId) ||+ execution.id === parent.id ||+ execution.agentIds.length === 0 ||+ execution.agentIds.some((agentId) => !parent.allowedAgentIds.includes(agentId))+ ) {+ throw new Error('The parent has not authorized this child to receive run files.');+ }+ const existing = executions.get(execution.id);+ if (existing != null) {+ if (JSON.stringify(existing) !== JSON.stringify(execution)) {+ throw new Error('A shared-file execution identity cannot be reassigned.');+ }+ return;+ }+ executions.set(execution.id, structuredClone(execution));+ audit({ action: 'inherit', scope, executionId: execution.id, fileIds: [...inputs] });+ }++ function canRead(actor: RunFileActor, file: TFile): boolean {+ if (inputs.has(file.file_id)) return true;+ const provenance = file.metadata?.runFile;+ if (provenance?.runId !== scope.runId) return false;+ if (actor.executionId === provenance.executionId && actor.agentId === provenance.agentId) {+ return true;+ }+ let parentId = provenance.parentExecutionId;+ let parentAgentId = provenance.parentAgentId;+ const visited = new Set<string>();+ while (parentId != null && !visited.has(parentId)) {+ if (parentId === actor.executionId && parentAgentId === actor.agentId) return true;+ visited.add(parentId);+ const parent = executions.get(parentId);+ parentId = parent?.parentId;+ parentAgentId = parent?.parentAgentId;+ }+ return (+ policy.allowSiblingSharing && provenance.recipientAgentIds?.includes(actor.agentId) === true+ );+ }++ async function refreshFiles(): Promise<void> {+ assertActive();+ hasLoadedPublications = false;+ let published: TFile[];+ let observedRevision: number;+ do {+ observedRevision = publicationRevision;+ published = await store.list(scope);+ assertActive();+ } while (observedRevision !== publicationRevision);+ assertActive();+ const retainedIds = new Set(published.map((file) => file.file_id));+ for (const fileId of files.keys()) {+ if (!inputs.has(fileId) && !retainedIds.has(fileId)) files.delete(fileId);+ }+ for (const file of published) {+ if (+ owns(file) &&+ file.conversationId === scope.conversationId &&+ file.metadata?.runFile?.runId === scope.runId+ ) {+ if (!files.has(file.file_id) && files.size >= policy.maxFiles) {+ throw new Error('The shared-file manifest exceeds the configured file limit.');+ }+ files.set(file.file_id, structuredClone(file));+ }+ }+ hasLoadedPublications = true;+ }++ async function refresh(signal?: AbortSignal): Promise<void> {+ assertActive(signal);+ // Concurrent graph members share the query, but each caller retains its own cancellation.+ pendingRefresh ??= refreshFiles().finally(() => {+ pendingRefresh = undefined;+ });+ await pendingRefresh;+ assertActive(signal);+ }++ async function getFiles(+ actor: RunFileActor,+ signal?: AbortSignal,+ mode: RunFileReadMode = 'refresh',+ ): Promise<TFile[]> {+ executionFor(actor, signal);+ // Unrelated tools reuse the catalog, but must join an in-flight refresh so a+ // newer preparation cannot reinstall a deleted file from an older snapshot.+ if (mode === 'refresh' || !hasLoadedPublications || pendingRefresh != null) {+ await refresh(signal);+ }+ return [...files.values()]+ .filter((file) => canRead(actor, file))+ .map((file) => structuredClone(file));+ }++ async function list(actor: RunFileActor, signal?: AbortSignal): Promise<RunFileEntry[]> {+ return describeRunFiles(await getFiles(actor, signal), scope.runId);+ }++ function stage(actor: RunFileActor, artifact: TArtifact): void {+ executionFor(actor);+ if (!artifact.id || !artifact.filename)+ throw new Error('The generated artifact has no identity.');+ const key = JSON.stringify([actor.executionId, actor.agentId, artifact.id]);+ const existing = artifacts.get(key);+ if (existing && JSON.stringify(existing.artifact) !== JSON.stringify(artifact)) {+ throw new Error('A generated artifact identity cannot be reused for different output.');+ }+ if (!existing && artifacts.size + files.size >= policy.maxFiles) {+ throw new Error('The shared-file manifest exceeds the configured file limit.');+ }+ artifacts.set(key, { actor: { ...actor }, artifact: structuredClone(artifact) });+ }++ function discardArtifacts(actor: RunFileActor): void {+ executionFor(actor);+ for (const [key, staged] of artifacts) {+ if (+ staged.actor.executionId === actor.executionId &&+ staged.actor.agentId === actor.agentId+ ) {+ artifacts.delete(key);+ }+ }+ }++ async function publish(+ actor: RunFileActor,+ artifactId: string,+ recipientAgentIds: string[] = [],+ signal?: AbortSignal,+ ): Promise<TFile> {+ const execution = executionFor(actor, signal);+ const key = JSON.stringify([actor.executionId, actor.agentId, artifactId]);+ const recipients = [...new Set(recipientAgentIds)].sort();+ const knownAgents = new Set<string>();+ for (const entry of executions.values()) {+ for (const agentId of [...entry.agentIds, ...entry.allowedAgentIds]) knownAgents.add(agentId);+ }+ if (+ recipients.length > 0 &&+ (!policy.allowSiblingSharing || recipients.some((agentId) => !knownAgents.has(agentId)))+ ) {+ throw new Error('The sharing policy does not authorize the requested recipients.');+ }+ const existing = publications.get(key);+ if (existing) {+ const file = await existing;+ assertActive(signal);+ if (+ JSON.stringify(file.metadata?.runFile?.recipientAgentIds ?? []) !==+ JSON.stringify(recipients)+ ) {+ throw new Error('A publication cannot be retried with different recipients.');+ }+ return structuredClone(file);+ }+ const publishPromise = (async () => {+ await refresh(signal);+ const restored = [...files.values()].find(+ (file) =>+ file.metadata?.runFile?.executionId === actor.executionId &&+ file.metadata.runFile.agentId === actor.agentId &&+ file.metadata.runFile.sourceFileId === artifactId,+ );+ if (restored) {+ if (+ JSON.stringify(restored.metadata?.runFile?.recipientAgentIds ?? []) !==+ JSON.stringify(recipients)+ ) {+ throw new Error('A publication cannot be retried with different recipients.');+ }+ return restored;+ }+ const staged = artifacts.get(key);+ if (!staged) throw new Error('Only artifacts generated by this execution can be published.');+ if (files.size + pendingPublications >= policy.maxFiles) {+ throw new Error('The shared-file manifest exceeds the configured file limit.');+ }+ pendingPublications++;+ try {+ const provenance: RunFileProvenance = {+ runId: scope.runId,+ executionId: actor.executionId,+ agentId: actor.agentId,+ parentExecutionId: execution.parentId,+ parentAgentId: execution.parentAgentId,+ sourceFileId: artifactId,+ publishedAt: new Date(now()).toISOString(),+ inputFileIds: [...inputs],+ recipientAgentIds: recipients,+ };+ const file = await store.publish({ scope, artifact: staged.artifact, provenance, signal });+ assertActive(signal);+ if (+ !owns(file) ||+ file.conversationId !== scope.conversationId ||+ file.metadata?.runFile?.runId !== scope.runId ||+ file.metadata.runFile.executionId !== actor.executionId ||+ file.metadata.runFile.sourceFileId !== artifactId ||+ file.metadata.runFile.agentId !== actor.agentId ||+ JSON.stringify(file.metadata.runFile.recipientAgentIds ?? []) !==+ JSON.stringify(recipients)+ )+ throw new Error('The artifact store returned a file outside this publication.');+ files.set(file.file_id, structuredClone(file));+ artifacts.delete(key);+ publicationRevision++;+ audit({+ action: 'publish',+ scope,+ ...actor,+ fileIds: [file.file_id],+ recipientAgentIds: recipients,+ });+ return file;+ } finally {+ pendingPublications--;+ }+ })();+ publications.set(key, publishPromise);+ try {+ return structuredClone(await publishPromise);+ } finally {+ publications.delete(key);+ }+ }++ return { register, getFiles, list, stage, discardArtifacts, publish, close };+}diff --git a/packages/api/src/agents/files/runtime.spec.ts b/packages/api/src/agents/files/runtime.spec.tsnew file mode 100644index 0000000000..aaf82c9e9d--- /dev/null+++ b/packages/api/src/agents/files/runtime.spec.ts@@ -0,0 +1,389 @@+jest.mock('@librechat/agents', () => ({+ ...jest.requireActual('@librechat/agents'),+ SUBAGENT_CONTEXT_VERSION: 1,+ Run: { create: jest.fn().mockResolvedValue({}) },+}));++import { z } from 'zod';+import { ImageDetail } from 'librechat-data-provider';+import { Run, InMemorySubagentTaskStore } from '@librechat/agents';+import { tool } from '@librechat/agents/langchain/tools';+import type { LCTool, SubagentExecutionContext } from '@librechat/agents';+import type { StructuredToolInterface } from '@librechat/agents/langchain/tools';+import type { RunFileSession } from './session';+import * as runtime from './runtime';+import { createRun } from '../run';++type RunAgent = Parameters<typeof createRun>[0]['agents'][number];++interface BuiltAgentInput {+ agentId: string;+ graphTools?: StructuredToolInterface[];+ tools?: StructuredToolInterface[];+ toolDefinitions?: Array<{ name: string }>;+ subagentConfigs?: Array<{+ agentInputs?: BuiltAgentInput;+ agents?: BuiltAgentInput[];+ }>;+}++function makeSession(active = true) {+ return {+ activate: jest.fn(() => active),+ isActive: () => active,+ prepare: jest.fn(async () => ({})),+ complete: jest.fn(+ async (_input: Parameters<RunFileSession['complete']>[0], result: { content: string }) =>+ result,+ ),+ list: jest.fn(async () => ({ files: [], artifacts: [] })),+ publish: jest.fn(async () => ({+ file_id: 'durable-file',+ filename: 'results.csv',+ user: 'owner',+ bytes: 1,+ embedded: false,+ filepath: '/files/results.csv',+ object: 'file' as const,+ type: 'text/csv',+ usage: 0,+ })),+ capture: jest.fn(async () => true),+ withCodeExecution: async (_agentId, _context, _signal, execute) => execute(),+ prepareTools: jest.fn(async () => undefined),+ actorFor: jest.fn((agentId: string) => ({ agentId, executionId: 'root-run' })),+ close: jest.fn(async () => undefined),+ } satisfies RunFileSession;+}++const identity: SubagentExecutionContext = {+ rootRunId: 'root-run',+ hookSessionId: 'root-run',+ depth: 1,+ ancestry: [+ {+ subagentRunId: 'child-execution',+ subagentType: 'worker',+ subagentKind: 'agent',+ subagentAgentId: 'worker',+ parentRunId: 'root-run',+ parentAgentId: 'parent',+ parentToolCallId: 'spawn-call',+ },+ ],+};++function agent(id: string, extra: Partial<RunAgent> = {}): RunAgent {+ return {+ id,+ name: id,+ description: null,+ avatar: null,+ created_at: 0,+ provider: 'openAI',+ endpoint: 'openAI',+ model: 'gpt-4o',+ model_parameters: {+ model: 'gpt-4o',+ temperature: null,+ maxContextTokens: null,+ max_context_tokens: null,+ max_output_tokens: null,+ top_p: null,+ frequency_penalty: null,+ presence_penalty: null,+ },+ tools: [],+ ...extra,+ };+}++function team(reader: RunAgent, writer: RunAgent): RunAgent {+ return agent('parent', {+ subagents: { enabled: true, allowSelf: false },+ subagentGraphConfigs: [+ {+ definition: {+ type: 'team',+ name: 'Team',+ description: 'Reader and writer',+ agent_ids: ['reader', 'writer'],+ edges: [],+ entry_agent_id: 'reader',+ result_agent_id: 'writer',+ },+ memberConfigs: [reader, writer],+ },+ ],+ });+}++async function create(+ session: RunFileSession,+ agents = [agent('parent')],+ options: Partial<Parameters<typeof createRun>[0]> = {},+) {+ await createRun({+ agents,+ runFiles: session,+ runId: 'root-run',+ conversationId: 'conversation',+ signal: new AbortController().signal,+ ...options,+ });+ return (Run.create as jest.Mock).mock.calls[0][0] as {+ subagentContext?: Pick<RunFileSession, 'prepare' | 'complete'>;+ subagentTasks?: Parameters<typeof createRun>[0]['subagentTasks'];+ graphConfig: {+ agents: BuiltAgentInput[];+ };+ };+}++describe('run file SDK bridge', () => {+ beforeEach(() => jest.clearAllMocks());++ it('registers callable tools on parent and explicit children only for an active session', async () => {+ const session = makeSession();+ const config = await create(session, [+ agent('parent', {+ subagents: { enabled: true, allowSelf: false, agent_ids: ['worker'], shareFiles: true },+ subagentAgentConfigs: [agent('worker')],+ }),+ ]);+ expect(session.activate).toHaveBeenCalledWith(+ 'root-run',+ 'conversation',+ ['parent'],+ expect.any(AbortSignal),+ );+ expect(config.subagentContext).toEqual({+ prepare: session.prepare,+ complete: session.complete,+ });+ const parent = config.graphConfig.agents[0];+ const child = parent.subagentConfigs?.[0].agentInputs;+ for (const input of [parent, child]) {+ expect(input?.graphTools?.map((tool) => tool.name)).toEqual([+ 'list_run_files',+ 'publish_artifact',+ ]);+ }+ const signal = new AbortController().signal;+ await child!.graphTools![0].invoke({}, { metadata: { executionContext: identity }, signal });+ expect(session.list).toHaveBeenCalledWith('worker', identity, signal);+ const result = await child!.graphTools![1].invoke(+ { artifact_id: 'code-call:output', recipient_agent_ids: ['reviewer'] },+ { metadata: { executionContext: identity }, signal },+ );+ expect(session.publish).toHaveBeenCalledWith(+ 'worker',+ identity,+ 'code-call:output',+ ['reviewer'],+ signal,+ );+ expect(JSON.parse(result)).toEqual({ file_id: 'durable-file', filename: 'results.csv' });+ });++ it('keeps the adapter and tools absent when the opt-in is off', async () => {+ const config = await create(makeSession(false), [+ agent('parent', {+ subagents: { enabled: true, allowSelf: false, agent_ids: ['worker'] },+ subagentAgentConfigs: [agent('worker')],+ }),+ ]);+ expect(config.subagentContext).toBeUndefined();+ const parent = config.graphConfig.agents[0];+ expect(parent.graphTools).toBeUndefined();+ expect(parent.subagentConfigs?.[0].agentInputs?.graphTools).toBeUndefined();+ });++ it.each(['direct', 'handoff'] as const)(+ 'distinguishes a nondelegating root %s member from its subagent instance',+ async (edgeType) => {+ const worker = agent('worker', { subagents: { enabled: false, shareFiles: true } });+ const config = await create(makeSession(), [+ agent('parent', {+ subagents: { enabled: true, allowSelf: false, agent_ids: ['worker'], shareFiles: true },+ subagentAgentConfigs: [worker],+ edges: [{ from: 'parent', to: 'worker', edgeType }],+ }),+ worker,+ agent('delegator', { subagents: { enabled: true, allowSelf: true } }),+ ]);+ const [parent, rootWorker, delegator] = config.graphConfig.agents;+ expect(rootWorker.agentId).toBe('worker');+ expect(rootWorker.graphTools).toBeUndefined();+ const childWorker = parent.subagentConfigs?.[0].agentInputs;+ expect(childWorker?.agentId).toBe(rootWorker.agentId);+ for (const input of [parent, delegator, childWorker]) {+ expect(input?.graphTools?.map((entry) => entry.name)).toEqual([+ 'list_run_files',+ 'publish_artifact',+ ]);+ }+ },+ );++ it('exposes tools to delegated team members without exposing them to their root instances', async () => {+ const reader = agent('reader');+ const writer = agent('writer', { subagents: { enabled: false } });+ const config = await create(makeSession(), [+ agent('parent', {+ subagents: { enabled: true, allowSelf: false, shareFiles: true },+ subagentGraphConfigs: [+ {+ definition: {+ type: 'team',+ name: 'Team',+ description: 'Reader and writer',+ agent_ids: ['reader', 'writer'],+ edges: [{ from: 'reader', to: 'writer', edgeType: 'direct' }],+ entry_agent_id: 'reader',+ result_agent_id: 'writer',+ },+ memberConfigs: [reader, writer],+ },+ ],+ }),+ reader,+ writer,+ ]);+ const [parent, rootReader, rootWriter] = config.graphConfig.agents;+ expect(rootReader.graphTools).toBeUndefined();+ expect(rootWriter.graphTools).toBeUndefined();+ const team = parent.subagentConfigs?.[0].agents;+ expect(team?.map((member) => member.agentId)).toEqual(['reader', 'writer']);+ for (const member of team ?? []) {+ expect(member.graphTools?.map((entry) => entry.name)).toEqual([+ 'list_run_files',+ 'publish_artifact',+ ]);+ }+ });++ it('keeps shared children foreground when the host supplies detached task support', async () => {+ const subagentTasks = { scopeId: 'owner:conversation', store: new InMemorySubagentTaskStore() };+ const config = await create(+ makeSession(),+ [agent('parent', { subagents: { enabled: true, allowSelf: true }, toolRegistry: new Map() })],+ { subagentTasks },+ );+ expect(config.subagentTasks).toBeUndefined();+ expect(+ config.graphConfig.agents[0].toolDefinitions?.map((definition) => definition.name),+ ).not.toContain('check_background_task');+ expect(config.graphConfig.agents[0].subagentConfigs).toHaveLength(1);+ });++ it('routes named tool implementations through host preparation and capture', async () => {+ const direct = tool(async () => '', {+ name: 'execute_code',+ description: 'Execute code',+ schema: z.object({}),+ });+ const invoke = jest.spyOn(direct, 'invoke');+ const definition: LCTool = {+ name: 'execute_code',+ description: 'Execute code',+ parameters: { type: 'object', properties: {} },+ };+ const original = agent('parent', {+ tools: [direct],+ toolDefinitions: [definition],+ subagents: { enabled: true, allowSelf: false, agent_ids: ['worker'] },+ subagentAgentConfigs: [agent('worker', { tools: [direct], toolDefinitions: [definition] })],+ });+ const config = await create(makeSession(), [original]);+ const parent = config.graphConfig.agents[0];+ for (const input of [parent, parent.subagentConfigs?.[0].agentInputs]) {+ expect(input?.tools).toEqual([]);+ expect(input?.toolDefinitions).toContainEqual(definition);+ }+ expect(original.tools).toHaveLength(1);+ expect(invoke).not.toHaveBeenCalled();+ });++ it('rejects direct tools without a host execution definition', async () => {+ const direct = tool(async () => '', {+ name: 'execute_code',+ description: 'Execute',+ schema: z.object({}),+ });+ await expect(create(makeSession(), [agent('parent', { tools: [direct] })])).rejects.toThrow(+ 'host-dispatched tools',+ );+ expect(Run.create).not.toHaveBeenCalled();+ });++ it('rejects sharing before constructing an SDK run without execution identity support', async () => {+ jest.spyOn(runtime, 'isRunFileSharingSupported').mockReturnValue(false);+ await expect(create(makeSession())).rejects.toThrow('subagent context support');+ expect(Run.create).not.toHaveBeenCalled();+ });++ it('rejects alternate ingresses that enable sharing without a file host', async () => {+ await expect(+ createRun({+ agents: [+ agent('parent', {+ subagents: { enabled: true, shareFiles: true },+ }),+ ],+ appConfig: {+ endpoints: { agents: { fileSharing: { enabled: true } } },+ } as Parameters<typeof createRun>[0]['appConfig'],+ signal: new AbortController().signal,+ }),+ ).rejects.toThrow('a file host is required');+ expect(Run.create).not.toHaveBeenCalled();+ });++ it('preserves a saved sharing preference without activating it when subagents are disabled', async () => {+ const config = await create(+ makeSession(false),+ [agent('parent', { subagents: { enabled: false, shareFiles: true } })],+ {+ runFiles: undefined,+ appConfig: {+ endpoints: { agents: { fileSharing: { enabled: true } } },+ } as Parameters<typeof createRun>[0]['appConfig'],+ },+ );+ expect(config.subagentContext).toBeUndefined();+ expect(config.graphConfig.agents[0].graphTools).toBeUndefined();+ });++ it.each([+ agent('writer', { provider: 'anthropic' }),+ agent('writer', { endpoint: 'restricted-endpoint' }),+ agent('writer', { imageDetail: ImageDetail.high }),+ agent('writer', { imageDetail: ImageDetail.low }),+ agent('writer', { imageDetail: ImageDetail.auto }),+ agent('writer', {+ model_parameters: { ...agent('reader').model_parameters, model: 'claude-sonnet' },+ }),+ agent('writer', {+ model_parameters: { ...agent('reader').model_parameters, useResponsesApi: true },+ }),+ ])(+ 'rejects incompatible team document formats before injecting shared files (%j)',+ async (writer) => {+ await expect(create(makeSession(), [team(agent('reader'), writer)])).rejects.toThrow(+ 'same provider',+ );+ expect(Run.create).not.toHaveBeenCalled();+ },+ );++ it.each([undefined, ImageDetail.auto, ImageDetail.low, ImageDetail.high])(+ 'accepts matching team image-detail settings (%s)',+ async (imageDetail) => {+ const config = await create(makeSession(), [+ team(agent('reader', { imageDetail }), agent('writer', { imageDetail })),+ ]);+ expect(config.graphConfig.agents[0].subagentConfigs?.[0].agents).toHaveLength(2);+ },+ );+});diff --git a/packages/api/src/agents/files/runtime.ts b/packages/api/src/agents/files/runtime.tsnew file mode 100644index 0000000000..4845a5318d--- /dev/null+++ b/packages/api/src/agents/files/runtime.ts@@ -0,0 +1,87 @@+import { z } from 'zod';+import * as agentsSdk from '@librechat/agents';+import { tool } from '@librechat/agents/langchain/tools';+import type { GenericTool, LCTool, SubagentExecutionContext } from '@librechat/agents';+import type { RunFileSession } from './session';++export const LIST_RUN_FILES_TOOL = 'list_run_files';+export const PUBLISH_ARTIFACT_TOOL = 'publish_artifact';++/** Older SDKs cannot distinguish simultaneous copies of the same agent. */+export function isRunFileSharingSupported(): boolean {+ return (agentsSdk as { SUBAGENT_CONTEXT_VERSION?: number }).SUBAGENT_CONTEXT_VERSION === 1;+}++/** Every configured tool must execute through host authorization and artifact capture. */+export function eventOnlyRunFileTools(+ tools: GenericTool[] | undefined,+ definitions: readonly LCTool[],+): GenericTool[] | undefined {+ if (tools == null || tools.length === 0) return tools;+ const eventTools = new Set(definitions.map((definition) => definition.name));+ for (const candidate of tools) {+ if (+ candidate == null ||+ typeof candidate.name !== 'string' ||+ typeof candidate.invoke !== 'function' ||+ !eventTools.has(candidate.name)+ ) {+ throw new Error('Run file sharing requires host-dispatched tools with explicit definitions.');+ }+ }+ // The definitions bind the model; removing direct instances sends execution+ // through ON_TOOL_EXECUTE, including private workspace setup and capture.+ return [];+}++/** In-graph tools receive execution metadata stamped by the SDK's owning ToolNode. */+export function createRunFileTools(+ session: RunFileSession,+ agentId: string,+ runSignal: AbortSignal,+): GenericTool[] {+ const list = tool(+ async (_input, config) => {+ const context = config.metadata?.executionContext as SubagentExecutionContext | undefined;+ return JSON.stringify(await session.list(agentId, context, config.signal ?? runSignal));+ },+ {+ name: LIST_RUN_FILES_TOOL,+ description:+ 'List the files this execution may read and its unpublished output artifact IDs. ' ++ 'Use this to discover files published by other authorized agents during this run. ' ++ 'Private output versions remain available across sandbox calls during this run. ' ++ 'The same filename may have multiple artifact IDs, listed in creation order; publish the version you want to return when ready. ' ++ "When delegating a task that returns files, ask the producing subagent to publish its outputs before returning. A parent cannot publish a child's private artifact IDs.",+ schema: z.object({}).strict(),+ },+ );+ const publish = tool(+ async ({ artifact_id, recipient_agent_ids }, config) => {+ const context = config.metadata?.executionContext as SubagentExecutionContext | undefined;+ const file = await session.publish(+ agentId,+ context,+ artifact_id,+ recipient_agent_ids,+ config.signal ?? runSignal,+ );+ return JSON.stringify({ file_id: file.file_id, filename: file.filename });+ },+ {+ name: PUBLISH_ARTIFACT_TOOL,+ description:+ "Publish one of this execution's own output artifacts from list_run_files as a durable downloadable file for " ++ 'the parent and user when ready. Each artifact ID selects an immutable output version, even after the working file changes. ' ++ 'Outputs stay private until this succeeds. Optional sibling agent ' ++ 'recipients must be authorized by the run sharing policy.',+ schema: z+ .object({+ artifact_id: z.string().min(1).describe('The artifact_id returned by list_run_files.'),+ recipient_agent_ids: z.array(z.string().min(1)).optional(),+ })+ .strict(),+ },+ );+ return [list, publish];+}diff --git a/packages/api/src/agents/files/session.spec.ts b/packages/api/src/agents/files/session.spec.tsnew file mode 100644index 0000000000..ad786df7cc--- /dev/null+++ b/packages/api/src/agents/files/session.spec.ts@@ -0,0 +1,628 @@+import { createHash } from 'node:crypto';+import { FileContext, FileSources } from 'librechat-data-provider';+import type { SubagentExecutionContext } from '@librechat/agents';+import type { TFile } from 'librechat-data-provider';+import type { RunArtifactDescriptor } from '~/files/code/publication';+import type { RunFileSessionDeps } from './session';+import type { ServerRequest } from '~/types';+import { createRunFileSession, getAuthorizedRunFileSnapshot } from './session';+import { AgentAttachmentLimitError } from '../attachments';+import { createRunFileMessageEncoder } from './encode';++function setup(+ subagentsEnabled = true,+ options: {+ signal?: AbortSignal;+ ttlMs?: number;+ inputs?: TFile[];+ validateMessages?: RunFileSessionDeps['validateMessages'];+ encodeMessages?: RunFileSessionDeps['encodeMessages'];+ } = {},+) {+ const saved: TFile[] = [];+ const publishedSources: RunArtifactDescriptor[] = [];+ const publishedBytes: Buffer[] = [];+ const privateBytes = new Map<string, Buffer>();+ let workingBytes = Buffer.from('initial output');+ let nextSnapshot = 0;+ let publicationFailure: Error | undefined;+ const snapshots = {+ capture: jest.fn(async (_source?: RunArtifactDescriptor, signal?: AbortSignal) => {+ signal?.throwIfAborted();+ const snapshotId = `snapshot-${nextSnapshot++}`;+ privateBytes.set(snapshotId, Buffer.from(workingBytes));+ return {+ snapshotId,+ size: workingBytes.length,+ sha256: createHash('sha256').update(workingBytes).digest('hex'),+ };+ }),+ discard: jest.fn(async (snapshotId: string) => {+ privateBytes.delete(snapshotId);+ }),+ close: jest.fn(async () => {+ privateBytes.clear();+ }),+ };+ const read = jest.fn(async () => saved);+ const prepared = jest.fn(async () => undefined);+ const emit = jest.fn(async () => undefined);+ const session = createRunFileSession({+ userId: 'user',+ createdAt: Date.now(),+ policy: {+ enabled: true,+ allowSiblingSharing: false,+ maxFiles: 20,+ maxPrivateBytes: 268_435_456,+ ttlMs: options.ttlMs ?? 60_000,+ },+ snapshots,+ getInputs: () => options.inputs ?? [],+ inputFileIds: new Set(options.inputs?.map((file) => file.file_id)),+ getAgent: (id) => {+ if (id === 'writer') {+ return { id, subagents: { enabled: true, allowSelf: false, agent_ids: ['reader'] } };+ }+ return {+ id,+ subagents:+ id === 'parent'+ ? {+ enabled: subagentsEnabled,+ allowSelf: false,+ shareFiles: true,+ graphs: [+ {+ type: 'team',+ name: 'Team',+ description: 'Analyze and write',+ agent_ids: ['reader', 'writer'],+ entry_agent_id: 'reader',+ result_agent_id: 'writer',+ edges: [{ from: 'reader', to: 'writer', edgeType: 'direct' }],+ },+ ],+ }+ : undefined,+ };+ },+ listPublications: read,+ publish: async ({ scope, artifact, provenance }) => {+ if (publicationFailure) {+ const error = publicationFailure;+ publicationFailure = undefined;+ throw error;+ }+ publishedSources.push(artifact);+ publishedBytes.push(Buffer.from(privateBytes.get(artifact.snapshotId!)!));+ const file: TFile = {+ file_id: `durable-output-${saved.length}`,+ filename: artifact.name,+ type: 'text/csv',+ user: scope.userId,+ conversationId: scope.conversationId,+ bytes: 10,+ embedded: false,+ filepath: '/private/output.csv',+ object: 'file',+ usage: 0,+ source: FileSources.local,+ context: FileContext.run_artifact,+ metadata: { runFile: provenance },+ };+ saved.push(file);+ return file;+ },+ prepareAgent: prepared,+ validateMessages: options.validateMessages ?? jest.fn(),+ encodeMessages: options.encodeMessages ?? (async () => []),+ emit,+ });+ const context: SubagentExecutionContext = {+ rootRunId: 'run',+ hookSessionId: 'run',+ depth: 1,+ ancestry: [+ {+ subagentRunId: 'child-team',+ subagentType: 'team',+ subagentKind: 'graph',+ subagentAgentId: 'reader',+ parentRunId: 'run',+ parentAgentId: 'parent',+ parentToolCallId: 'spawn-call',+ },+ ],+ };+ const preparation = {+ executionContext: context,+ memberAgentIds: ['reader', 'writer'],+ signal: new AbortController().signal,+ resumed: false,+ };+ session.activate('run', 'conversation', ['parent'], options.signal);+ return {+ session,+ saved,+ context,+ preparation,+ read,+ prepared,+ publishedSources,+ publishedBytes,+ snapshots,+ emit,+ setWorkingBytes: (value: string) => {+ workingBytes = Buffer.from(value);+ },+ failNextPublication: (error: Error) => {+ publicationFailure = error;+ },+ };+}++it('returns publications from every graph member without granting sibling access', async () => {+ const { session, context, preparation } = setup();+ await session.prepare(preparation);+ await session.capture('writer', context, 'code-call', {+ session_id: 'writer-session',+ files: [{ id: 'output', name: 'results.csv' }],+ });+ const artifactId = (await session.list('writer', context)).artifacts[0].artifact_id;+ await session.publish('writer', context, artifactId);+ expect((await session.list('reader', context)).files).toHaveLength(0);+ expect((await session.list('parent')).files).toHaveLength(1);+ const result = await session.complete(preparation, { content: 'Analysis finished.' });+ expect(result.content).toContain('durable-output');+ expect(result.content).toContain('results.csv');+});++it('prepares every graph member from one read and reuses the snapshot for the catalog', async () => {+ const { session, preparation, read, prepared } = setup();+ const result = await session.prepare(preparation);+ expect(read).toHaveBeenCalledTimes(1);+ expect(prepared).toHaveBeenCalledTimes(2);+ expect(result.agentSessions?.reader.codeSessionKey).not.toBe(+ result.agentSessions?.writer.codeSessionKey,+ );+});++it.each([{ totalSizeLimit: 1 }, { fileLimit: 1 }])(+ 'checks later team members before encoding shared files or provisioning resources (%j)',+ async (limits) => {+ const input: TFile = {+ file_id: 'shared-report',+ filename: 'report.pdf',+ type: 'application/pdf',+ bytes: 600_000,+ user: 'user',+ embedded: false,+ filepath: '/files/report.pdf',+ object: 'file',+ usage: 0,+ source: FileSources.local,+ llmDeliveryPath: 'provider',+ metadata: { destinationChosen: true },+ };+ const writerAttachments = [{ ...input, file_id: 'writer-setup', context: FileContext.agents }];+ const document = {+ type: 'file',+ file: { filename: 'report.pdf', file_data: 'data:application/pdf;base64,cGRm' },+ };+ const encodeDocuments = jest.fn(async () => ({ documents: [document] }));+ const fileConfig: NonNullable<ServerRequest['config']>['fileConfig'] = {+ endpoints: { openAI: limits },+ };+ const encoder = createRunFileMessageEncoder({+ req: { body: {}, config: { fileConfig } } as ServerRequest,+ getAgent: (id) => ({+ provider: 'openAI',+ agentContextAttachments: id === 'writer' ? writerAttachments : [],+ }),+ encodeDocuments,+ encodeImages: async () => ({ image_urls: [] }),+ encodeAudios: async () => ({ audios: [] }),+ encodeVideos: async () => ({ videos: [] }),+ extractText: async () => undefined,+ getStrategyFunctions: jest.fn(),+ });+ const validateMessages = jest.fn(encoder.validate);+ const { session, preparation, prepared, read } = setup(true, {+ inputs: [input],+ validateMessages,+ encodeMessages: encoder.encode,+ });+ try {+ await expect(session.prepare(preparation)).rejects.toThrow(AgentAttachmentLimitError);+ expect(prepared).not.toHaveBeenCalled();+ expect(encodeDocuments).not.toHaveBeenCalled();++ writerAttachments.splice(0);+ const result = await session.prepare(preparation);+ expect(prepared).toHaveBeenCalledTimes(2);+ expect(encodeDocuments).toHaveBeenCalledTimes(1);+ expect(result.messages?.[1].content).toEqual(expect.arrayContaining([document]));+ expect(read).toHaveBeenCalledTimes(2);++ validateMessages.mockClear();+ const resumed = await session.prepare({ ...preparation, resumed: true });+ expect(resumed.messages).toEqual([]);+ expect(validateMessages).not.toHaveBeenCalled();+ expect(encodeDocuments).toHaveBeenCalledTimes(1);+ } finally {+ await session.close();+ }+ },+);++it('reuses publications for unrelated batches while preparing and authorizing each execution', async () => {+ const { session, preparation, context, read, prepared } = setup();+ try {+ await session.prepareTools('parent', undefined, preparation.signal, 'snapshot');+ await session.prepareTools('parent', undefined, preparation.signal, 'snapshot');+ expect(read).toHaveBeenCalledTimes(1);+ expect(prepared).toHaveBeenCalledTimes(2);+ expect(prepared).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({ actor: { executionId: 'run', agentId: 'parent' }, revision: 1 }),+ );+ expect(prepared).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({ actor: { executionId: 'run', agentId: 'parent' }, revision: 2 }),+ );++ await expect(+ session.prepareTools('writer', context, preparation.signal, 'snapshot'),+ ).rejects.toThrow('not authorized');+ expect(read).toHaveBeenCalledTimes(1);+ expect(prepared).toHaveBeenCalledTimes(2);++ await session.prepare(preparation);+ expect(read).toHaveBeenCalledTimes(2);+ await session.prepareTools('writer', context, preparation.signal, 'snapshot');+ expect(read).toHaveBeenCalledTimes(2);+ expect(prepared).toHaveBeenLastCalledWith(+ expect.objectContaining({ actor: { executionId: 'child-team', agentId: 'writer' } }),+ );+ await session.prepareTools('writer', context, preparation.signal);+ expect(read).toHaveBeenCalledTimes(3);+ } finally {+ await session.close();+ }+});++it('keeps a retained sharing preference inactive while the master subagent setting is disabled', () => {+ const { session, read } = setup(false);+ expect(session.isActive()).toBe(false);+ expect(read).not.toHaveBeenCalled();+ expect(+ getAuthorizedRunFileSnapshot({+ policy: {+ enabled: true,+ allowSiblingSharing: false,+ maxFiles: 100,+ maxPrivateBytes: 268_435_456,+ ttlMs: 60_000,+ },+ agent: { subagents: { enabled: false, shareFiles: true } },+ files: [],+ }),+ ).toBeUndefined();+});++it('grants a nested publication to the dispatching parent and ancestors, not its graph peers', async () => {+ const { session, context, preparation } = setup();+ await session.prepare(preparation);+ const nested: SubagentExecutionContext = {+ ...context,+ depth: 2,+ ancestry: [+ ...context.ancestry,+ {+ subagentRunId: 'nested',+ subagentType: 'reader',+ subagentKind: 'agent',+ subagentAgentId: 'reader',+ parentRunId: 'child-team',+ parentAgentId: 'writer',+ parentToolCallId: 'nested-spawn',+ },+ ],+ };+ await session.prepare({ ...preparation, executionContext: nested, memberAgentIds: ['reader'] });+ await session.capture('reader', nested, 'nested-code', {+ session_id: 'nested-sandbox',+ files: [{ id: 'output', name: 'output.csv' }],+ });+ const artifactId = (await session.list('reader', nested)).artifacts[0].artifact_id;+ await session.publish('reader', nested, artifactId);+ expect((await session.list('writer', context)).files).toHaveLength(1);+ expect((await session.list('parent')).files).toHaveLength(1);+ expect((await session.list('reader', context)).files).toHaveLength(0);+});++it('rejects substituted ancestry and retains its own copy of the SDK lineage', async () => {+ const { session, context, preparation } = setup();+ await session.prepare(preparation);+ Object.assign(context.ancestry[0], { parentAgentId: 'stranger' });+ await expect(session.list('writer', context)).rejects.toThrow('not authorized');+ await expect(session.prepare(preparation)).rejects.toThrow('parent lineage');+});++it('does not republish inherited inputs and uses the storage identity for generated files', async () => {+ const { session, context, preparation, publishedSources } = setup();+ await session.prepare(preparation);+ await session.capture('writer', context, 'code-call', {+ session_id: 'execution-session',+ files: [+ { id: 'input', name: 'input.pdf', inherited: true, storage_session_id: 'input-storage' },+ { id: 'output', name: 'output.csv', storage_session_id: 'output-storage' },+ ],+ });+ const artifacts = (await session.list('writer', context)).artifacts;+ const artifactId = artifacts[0].artifact_id;+ expect(artifacts).toEqual([+ { artifact_id: expect.stringMatching(/:code-call:output$/), filename: 'output.csv' },+ ]);+ await expect(session.publish('writer', context, 'code-call:input')).rejects.toThrow(+ 'Only artifacts',+ );+ const file = await session.publish('writer', context, artifactId);+ expect(file.metadata?.runFile?.sourceFileId).toBe(artifactId);+ expect(publishedSources[0].sessionId).toBe('output-storage');+ expect((await session.list('writer', context)).artifacts).toHaveLength(0);+ await expect(session.publish('writer', context, artifactId)).resolves.toEqual(file);+});++it('retains immutable versions across inspect and overwrite calls until the child publishes', async () => {+ const { session, context, preparation, setWorkingBytes, publishedBytes, snapshots } = setup();+ await session.prepare(preparation);+ const output = { session_id: 'sandbox', files: [{ id: 'output', name: 'output.csv' }] };+ setWorkingBytes('draft');+ await session.capture('writer', context, 'first', output);+ const firstId = (await session.list('writer', context)).artifacts[0].artifact_id;+ await session.withCodeExecution('writer', context, preparation.signal, async () => {+ await session.capture('writer', context, 'inspect', output);+ });+ expect((await session.list('writer', context)).artifacts).toEqual([+ { artifact_id: firstId, filename: 'output.csv' },+ ]);+ expect(snapshots.discard).toHaveBeenCalledWith('snapshot-1');+ await session.withCodeExecution('writer', context, preparation.signal, async () => {+ setWorkingBytes('revised');+ await session.capture('writer', context, 'revise', output);+ });+ const versions = (await session.list('writer', context)).artifacts;+ expect(versions).toHaveLength(2);+ expect(versions[0].artifact_id).toBe(firstId);+ expect((await session.list('parent')).files).toHaveLength(0);+ expect((await session.list('reader', context)).artifacts).toHaveLength(0);+ const first = await session.publish('writer', context, firstId);+ const second = await session.publish('writer', context, versions[1].artifact_id);+ expect(publishedBytes.map((buffer) => buffer.toString())).toEqual(['draft', 'revised']);+ expect(first.file_id).not.toBe(second.file_id);+ await expect(session.publish('writer', context, firstId)).resolves.toEqual(first);+ expect((await session.list('parent')).files).toHaveLength(2);+ expect((await session.list('writer', context)).artifacts).toHaveLength(0);+});++it('distinguishes new code generations even when a provider reuses both tool and output IDs', async () => {+ const { session, context, preparation, publishedSources } = setup();+ await session.prepare(preparation);+ const output = { session_id: 'sandbox', files: [{ id: 'reused-output', name: 'output.csv' }] };+ const generate = () =>+ session.withCodeExecution('writer', context, preparation.signal, async () => {+ await session.capture('writer', context, 'reused-call', output);+ });+ await generate();+ const firstId = (await session.list('writer', context)).artifacts[0].artifact_id;+ const first = await session.publish('writer', context, firstId);+ await generate();+ const secondId = (await session.list('writer', context)).artifacts[0].artifact_id;+ const second = await session.publish('writer', context, secondId);+ expect(secondId).not.toBe(firstId);+ expect(second.file_id).not.toBe(first.file_id);+ expect(publishedSources).toHaveLength(2);+ await expect(session.publish('writer', context, firstId)).resolves.toEqual(first);+});++it('keeps a reverted working version last without confusing it with an older matching draft', async () => {+ const { session, context, preparation, setWorkingBytes, publishedBytes } = setup();+ await session.prepare(preparation);+ for (const contents of ['draft', 'revised', 'draft']) {+ setWorkingBytes(contents);+ await session.capture('writer', context, 'reused-call', {+ session_id: 'sandbox',+ files: [{ id: 'output', name: 'analysis.csv' }],+ });+ }+ const versions = (await session.list('writer', context)).artifacts;+ expect(versions).toHaveLength(3);+ expect(new Set(versions.map((version) => version.artifact_id)).size).toBe(3);+ await session.publish('writer', context, versions[2].artifact_id);+ expect(publishedBytes[0].toString()).toBe('draft');+});++it('retains existing versions when another capture fails and permits publication retry', async () => {+ const { session, context, preparation, snapshots, failNextPublication } = setup();+ await session.prepare(preparation);+ const output = { session_id: 'sandbox', files: [{ id: 'output', name: 'analysis.csv' }] };+ await session.capture('writer', context, 'generate', output);+ const artifact = (await session.list('writer', context)).artifacts[0];+ snapshots.capture.mockRejectedValueOnce(new Error('Private artifact byte limit exceeded'));+ await expect(session.capture('writer', context, 'refine', output)).rejects.toThrow('byte limit');+ expect((await session.list('writer', context)).artifacts).toEqual([artifact]);+ failNextPublication(new Error('Storage temporarily unavailable'));+ await expect(session.publish('writer', context, artifact.artifact_id)).rejects.toThrow(+ 'temporarily',+ );+ expect(snapshots.discard).not.toHaveBeenCalled();+ expect((await session.list('writer', context)).artifacts).toEqual([artifact]);+ await session.publish('writer', context, artifact.artifact_id);+ expect(snapshots.discard).toHaveBeenCalledWith('snapshot-0');+ await session.close();+ expect(snapshots.close).toHaveBeenCalledTimes(1);+});++it('closes private snapshots on run cancellation and prevents further sandbox work', async () => {+ const controller = new AbortController();+ const { session, context, preparation, snapshots } = setup(true, { signal: controller.signal });+ await session.prepare(preparation);+ await session.capture('writer', context, 'generate', {+ session_id: 'sandbox',+ files: [{ id: 'output', name: 'analysis.csv' }],+ });+ controller.abort();+ await session.close();+ expect(snapshots.close).toHaveBeenCalledTimes(1);+ await expect(session.list('writer', context)).rejects.toThrow('expired');+ const execute = jest.fn(async () => undefined);+ expect(() => session.withCodeExecution('writer', context, preparation.signal, execute)).toThrow(+ 'expired',+ );+ expect(execute).not.toHaveBeenCalled();+});++it('cancels only the child snapshot download when that child execution is aborted', async () => {+ const { session, context, preparation, snapshots } = setup();+ await session.prepare(preparation);+ const controller = new AbortController();+ let opened!: () => void;+ const opening = new Promise<void>((resolve) => {+ opened = resolve;+ });+ snapshots.capture.mockImplementationOnce(async (_source, signal) => {+ opened();+ return new Promise((_resolve, reject) => {+ signal!.addEventListener('abort', () => reject(signal!.reason), { once: true });+ });+ });+ const operation = session.withCodeExecution('writer', context, controller.signal, () =>+ session.capture('writer', context, 'generate', {+ session_id: 'sandbox',+ files: [{ id: 'output', name: 'analysis.csv' }],+ }),+ );+ const observed = operation.catch((error: unknown) => error);+ await opening;+ controller.abort(new Error('Child stopped'));+ expect(await observed).toEqual(new Error('Child stopped'));+ expect((await session.list('writer', context)).artifacts).toHaveLength(0);+ expect(snapshots.close).not.toHaveBeenCalled();+ await expect(+ session.withCodeExecution('reader', context, preparation.signal, async () => 'still active'),+ ).resolves.toBe('still active');+ await session.close();+});++it('emits a durable publication even when private snapshot cleanup fails', async () => {+ const { session, context, preparation, snapshots, emit } = setup();+ await session.prepare(preparation);+ await session.capture('writer', context, 'generate', {+ session_id: 'sandbox',+ files: [{ id: 'output', name: 'analysis.csv' }],+ });+ const artifactId = (await session.list('writer', context)).artifacts[0].artifact_id;+ snapshots.discard.mockRejectedValueOnce(new Error('Temporary filesystem error'));+ const published = await session.publish('writer', context, artifactId);+ expect(emit).toHaveBeenCalledWith(expect.objectContaining({ file_id: published.file_id }));+ await session.close();+ expect(snapshots.close).toHaveBeenCalledTimes(1);+});++it('does not emit if cancellation arrives during cleanup after durable publication', async () => {+ const { session, context, preparation, snapshots, emit, saved } = setup();+ await session.prepare(preparation);+ await session.capture('writer', context, 'generate', {+ session_id: 'sandbox',+ files: [{ id: 'output', name: 'analysis.csv' }],+ });+ const artifactId = (await session.list('writer', context)).artifacts[0].artifact_id;+ const controller = new AbortController();+ snapshots.discard.mockImplementationOnce(async () => {+ controller.abort(new Error('Publication stopped'));+ });+ await expect(+ session.publish('writer', context, artifactId, [], controller.signal),+ ).rejects.toThrow('Publication stopped');+ expect(saved).toHaveLength(1);+ expect(emit).not.toHaveBeenCalled();+ await expect(session.publish('writer', context, artifactId)).resolves.toEqual(saved[0]);+ expect(emit).toHaveBeenCalledTimes(1);+ await session.close();+});++it('cleans up expired snapshots without needing another tool call', async () => {+ jest.useFakeTimers();+ try {+ const { session, context, preparation, snapshots } = setup(true, { ttlMs: 100 });+ await session.prepare(preparation);+ await session.capture('writer', context, 'generate', {+ session_id: 'sandbox',+ files: [{ id: 'output', name: 'analysis.csv' }],+ });+ await jest.advanceTimersByTimeAsync(100);+ expect(snapshots.close).toHaveBeenCalledTimes(1);+ await expect(session.list('parent')).rejects.toThrow('expired');+ await session.close();+ } finally {+ jest.useRealTimers();+ }+});++it('serializes code through capture within one actor while another actor progresses independently', async () => {+ const { session, context, preparation } = setup();+ await session.prepare(preparation);+ const events: string[] = [];+ let finishFirst!: () => void;+ const first = session.withCodeExecution('writer', context, preparation.signal, async () => {+ events.push('first-start');+ await new Promise<void>((resolve) => {+ finishFirst = resolve;+ });+ await session.capture('writer', context, 'first', {+ session_id: 'writer-sandbox',+ files: [{ id: 'one', name: 'one.csv' }],+ });+ events.push('first-captured');+ });+ const second = session.withCodeExecution('writer', context, preparation.signal, async () => {+ events.push('second-start');+ expect((await session.list('writer', context)).artifacts).toHaveLength(1);+ });+ await session.withCodeExecution('reader', context, preparation.signal, async () => {+ events.push('reader');+ });+ expect(events).toEqual(['first-start', 'reader']);+ finishFirst();+ await Promise.all([first, second]);+ expect(events).toEqual(['first-start', 'reader', 'first-captured', 'second-start']);+});++it('releases a failed code operation and never starts an aborted queued operation', async () => {+ const { session, context, preparation } = setup();+ await session.prepare(preparation);+ await expect(+ session.withCodeExecution('writer', context, preparation.signal, async () => {+ throw new Error('Code failed');+ }),+ ).rejects.toThrow('Code failed');+ const execute = jest.fn(async () => 'success');+ await expect(+ session.withCodeExecution('writer', context, AbortSignal.abort(), execute),+ ).rejects.toThrow();+ expect(execute).not.toHaveBeenCalled();+ await expect(+ session.withCodeExecution('writer', context, preparation.signal, execute),+ ).resolves.toBe('success');+});++it('restores published references without advertising stale private outputs on resume', async () => {+ const { session, context, preparation } = setup();+ const prepared = await session.prepare({ ...preparation, resumed: true });+ expect(prepared.messages).toEqual([]);+ expect((await session.list('writer', context)).private_artifact_recovery).toContain('Regenerate');+ await session.close();+ await expect(session.list('parent')).rejects.toThrow('expired');+});diff --git a/packages/api/src/agents/files/session.ts b/packages/api/src/agents/files/session.tsnew file mode 100644index 0000000000..b3657b7ba0--- /dev/null+++ b/packages/api/src/agents/files/session.ts@@ -0,0 +1,560 @@+import { createHash, randomUUID } from 'node:crypto';+import { HumanMessage } from '@librechat/agents/langchain';+import type { Agent, RunFileProvenance, TFile, TAgentsEndpoint } from 'librechat-data-provider';+import type { SubagentExecutionContext } from '@librechat/agents';+import type { BaseMessage } from '@librechat/agents/langchain';+import type {+ RunFileActor,+ RunFileManifest,+ RunFileScope,+ RunFileEntry,+ RunFileAudit,+ RunFileReadMode,+} from './manifest';+import type { RunArtifactDescriptor } from '~/files/code/publication';+import type { RunFileSnapshotStore } from './snapshots';+import type { RunFileMessageEncoder } from './encode';+import { createRunFileManifest, describeRunFiles } from './manifest';++export interface SharedRunArtifact {+ id: string;+ filename: string;+ sha256: string;+ source: RunArtifactDescriptor;+}++export function getAuthorizedRunFileSnapshot({+ policy,+ agent,+ files,+}: {+ policy?: TAgentsEndpoint['fileSharing'];+ agent: Pick<Agent, 'subagents'>;+ files: readonly TFile[];+}): readonly TFile[] | undefined {+ return policy?.enabled === true &&+ agent.subagents?.enabled === true &&+ agent.subagents.shareFiles === true+ ? files+ : undefined;+}++export interface RunFilePreparation {+ executionContext: SubagentExecutionContext;+ memberAgentIds: readonly string[];+ signal: AbortSignal;+ resumed: boolean;+}++export interface RunFileSessionDeps {+ policy?: TAgentsEndpoint['fileSharing'];+ userId: string;+ tenantId?: string;+ createdAt: number;+ audit?: (event: RunFileAudit) => void;+ getAgent: (id: string) => Pick<Agent, 'id' | 'subagents'> | undefined;+ getInputs: () => readonly TFile[];+ inputFileIds: ReadonlySet<string>;+ listPublications: (scope: RunFileScope) => Promise<TFile[]>;+ snapshots: Pick<RunFileSnapshotStore, 'capture' | 'discard' | 'close'>;+ publish: (params: {+ scope: RunFileScope;+ artifact: RunArtifactDescriptor;+ provenance: RunFileProvenance;+ signal?: AbortSignal;+ }) => Promise<TFile>;+ prepareAgent: (params: {+ actor: RunFileActor;+ files: TFile[];+ sessionKey: string;+ revision: number;+ signal: AbortSignal;+ }) => Promise<void>;+ validateMessages: RunFileMessageEncoder['validate'];+ encodeMessages: RunFileMessageEncoder['encode'];+ emit: (+ file: TFile & { messageId: string; toolCallId?: string; agentId: string },+ ) => Promise<void>;+}++export interface CapturedRunArtifact {+ session_id?: string;+ files?: Array<{+ id: string;+ name: string;+ session_id?: string;+ storage_session_id?: string;+ inherited?: boolean;+ }>;+}++export interface PreparedRunFiles {+ messages?: BaseMessage[];+ agentSessions?: Record<string, { codeSessionKey: string }>;+}++export interface RunFileSession {+ activate: (+ runId: string,+ conversationId: string,+ agentIds: string[],+ signal?: AbortSignal,+ ) => boolean;+ prepare: (input: RunFilePreparation) => Promise<PreparedRunFiles>;+ complete: (+ input: RunFilePreparation,+ result: { content: string },+ ) => Promise<{ content: string }>;+ list: (+ agentId: string,+ context?: SubagentExecutionContext,+ signal?: AbortSignal,+ ) => Promise<{+ files: RunFileEntry[];+ artifacts: Array<{ artifact_id: string; filename: string }>;+ private_artifact_recovery?: string;+ }>;+ capture: (+ agentId: string,+ context: SubagentExecutionContext | undefined,+ toolCallId: string,+ artifact: CapturedRunArtifact,+ codeExecutionContext?: RunArtifactDescriptor['codeExecutionContext'],+ ) => Promise<boolean>;+ withCodeExecution: <T>(+ agentId: string,+ context: SubagentExecutionContext | undefined,+ signal: AbortSignal,+ execute: () => Promise<T>,+ ) => Promise<T>;+ publish: (+ agentId: string,+ context: SubagentExecutionContext | undefined,+ artifactId: string,+ recipients?: string[],+ signal?: AbortSignal,+ ) => Promise<TFile>;+ prepareTools: (+ agentId: string,+ context: SubagentExecutionContext | undefined,+ signal: AbortSignal,+ mode?: RunFileReadMode,+ ) => Promise<void>;+ actorFor: (agentId: string, context?: SubagentExecutionContext) => RunFileActor;+ close: () => Promise<void>;+ isActive: () => boolean;+}++/** Coordinates the SDK's execution identities with file grants and host-owned tool contexts. */+export function createRunFileSession(deps: RunFileSessionDeps): RunFileSession {+ let manifest: RunFileManifest<SharedRunArtifact> | undefined;+ let scope: RunFileScope | undefined;+ let rootAgentId: string | undefined;+ const contexts = new Map<string, SubagentExecutionContext>();+ const members = new Map<string, readonly string[]>();+ const staged = new Map<string, Map<string, SharedRunArtifact>>();+ const lifetime = new AbortController();+ let expiryTimer: ReturnType<typeof setTimeout> | undefined;+ let runSignal: AbortSignal | undefined;+ let closing: Promise<void> | undefined;+ const codeOperations = new Map<string, Promise<void>>();+ const codeSignals = new Map<string, AbortSignal>();+ const preparations = new Map<string, number>();+ const resumedExecutions = new Set<string>();++ function nextPreparation(actor: RunFileActor): number {+ const key = JSON.stringify(actor);+ const next = (preparations.get(key) ?? 0) + 1;+ preparations.set(key, next);+ return next;+ }++ function allowedAgentIds(agentIds: readonly string[]): string[] {+ const allowed = new Set<string>();+ for (const id of agentIds) {+ const agent = deps.getAgent(id);+ if (!agent?.subagents?.enabled) continue;+ if (agent.subagents.allowSelf !== false) allowed.add(id);+ for (const childId of agent.subagents.agent_ids ?? []) allowed.add(childId);+ for (const graph of agent.subagents.graphs ?? []) {+ for (const member of graph.agent_ids) allowed.add(member);+ }+ }+ return [...allowed];+ }++ function activate(+ runId: string,+ conversationId: string,+ agentIds: string[],+ signal?: AbortSignal,+ ): boolean {+ const root = deps.getAgent(agentIds[0]);+ if (+ deps.policy?.enabled !== true ||+ root?.subagents?.enabled !== true ||+ root.subagents.shareFiles !== true+ )+ return false;+ if (scope != null) {+ if (scope.runId !== runId || scope.conversationId !== conversationId) {+ throw new Error('A shared-file session cannot be reused by another run.');+ }+ return true;+ }+ scope = { userId: deps.userId, tenantId: deps.tenantId, conversationId, runId };+ rootAgentId = agentIds[0];+ members.set(runId, [...agentIds]);+ manifest = createRunFileManifest({+ scope,+ policy: deps.policy,+ root: { id: runId, agentIds, allowedAgentIds: allowedAgentIds(agentIds) },+ inputFiles: deps.getInputs(),+ inputFileIds: deps.inputFileIds,+ createdAt: deps.createdAt,+ audit: deps.audit,+ store: {+ list: deps.listPublications,+ publish: ({ scope: publicationScope, artifact, provenance, signal }) =>+ deps.publish({ scope: publicationScope, artifact: artifact.source, provenance, signal }),+ },+ });+ runSignal = signal;+ signal?.addEventListener('abort', endRun, { once: true });+ expiryTimer = setTimeout(endRun, Math.max(0, deps.createdAt + deps.policy.ttlMs - Date.now()));+ expiryTimer.unref?.();+ if (signal?.aborted) endRun();+ return true;+ }++ function actorFor(agentId: string, context?: SubagentExecutionContext): RunFileActor {+ if (!scope || !manifest) throw new Error('Run file sharing is not active.');+ lifetime.signal.throwIfAborted();+ if (context == null) return { executionId: scope.runId, agentId };+ const leaf = context.ancestry[context.ancestry.length - 1];+ const registered = leaf && contexts.get(leaf.subagentRunId);+ if (!registered || lineageKey(context) !== lineageKey(registered)) {+ throw new Error('The child execution is not authorized for this shared-file run.');+ }+ return { executionId: leaf.subagentRunId, agentId };+ }++ function lineageKey(context: SubagentExecutionContext): string {+ return JSON.stringify([+ context.rootRunId,+ context.depth,+ context.ancestry.map((entry) => [+ entry.subagentRunId,+ entry.parentRunId,+ entry.parentAgentId,+ entry.parentToolCallId,+ entry.subagentType,+ entry.subagentKind,+ entry.subagentAgentId,+ ]),+ ]);+ }++ function sessionKey(actor: RunFileActor): string {+ return createHash('sha256')+ .update(JSON.stringify([scope?.tenantId, scope?.userId, scope?.runId, actor]))+ .digest('hex');+ }++ async function prepare(input: RunFilePreparation) {+ if (!manifest || !scope) return {};+ const { executionContext: context, memberAgentIds, signal } = input;+ const leaf = context.ancestry[context.ancestry.length - 1];+ if (context.rootRunId !== scope.runId || !leaf || context.depth !== context.ancestry.length) {+ throw new Error('Invalid shared-file execution lineage.');+ }+ const parentId = context.ancestry[context.ancestry.length - 2]?.subagentRunId ?? scope.runId;+ const parentContext = contexts.get(parentId);+ const expectedPrefix = parentContext?.ancestry ?? [];+ const prefix = {+ ...context,+ depth: context.depth - 1,+ ancestry: context.ancestry.slice(0, -1),+ };+ if (+ !leaf.parentAgentId ||+ !members.get(parentId)?.includes(leaf.parentAgentId) ||+ leaf.parentRunId !== parentId ||+ lineageKey(prefix) !==+ lineageKey({ ...context, depth: expectedPrefix.length, ancestry: expectedPrefix })+ ) {+ throw new Error('Invalid shared-file parent lineage.');+ }+ const registered = contexts.get(leaf.subagentRunId);+ if (registered && lineageKey(registered) !== lineageKey(context)) {+ throw new Error('A shared-file execution lineage cannot be reassigned.');+ }+ manifest.register({+ id: leaf.subagentRunId,+ parentId,+ parentAgentId: leaf.parentAgentId,+ agentIds: memberAgentIds,+ allowedAgentIds: allowedAgentIds(memberAgentIds),+ });+ contexts.set(leaf.subagentRunId, structuredClone(context));+ members.set(leaf.subagentRunId, [...memberAgentIds]);+ if (input.resumed) resumedExecutions.add(leaf.subagentRunId);+ const agentSessions: Record<string, { codeSessionKey: string }> = {};+ const preparations = await Promise.all(+ memberAgentIds.map(async (agentId) => {+ const actor = actorFor(agentId, context);+ const revision = nextPreparation(actor);+ const files = await manifest!.getFiles(actor, signal);+ const key = sessionKey(actor);+ if (!input.resumed) deps.validateMessages(files, agentId);+ return { actor, files, sessionKey: key, revision, signal };+ }),+ );+ await Promise.all(+ preparations.map(async (preparation) => {+ await deps.prepareAgent(preparation);+ const {+ actor: { agentId },+ sessionKey: key,+ } = preparation;+ agentSessions[agentId] = { codeSessionKey: key };+ }),+ );+ let messages: BaseMessage[] = [];+ if (!input.resumed && preparations.length > 0) {+ const {+ actor: { agentId },+ files,+ } = preparations[0];+ const catalog = describeRunFiles(files, scope.runId);+ messages = [+ new HumanMessage({+ content: `Files shared for this task (read-only inputs):\n${JSON.stringify(catalog)}\nUse list_run_files to discover later publications. Generated outputs remain private until publish_artifact succeeds.`,+ }),+ ...(await deps.encodeMessages(files, agentId)),+ ];+ }+ return { messages, agentSessions };+ }++ async function list(agentId: string, context?: SubagentExecutionContext, signal?: AbortSignal) {+ const actor = actorFor(agentId, context);+ const files = await manifest!.list(actor, signal);+ return {+ files,+ ...(resumedExecutions.has(actor.executionId)+ ? {+ private_artifact_recovery:+ 'Previously unpublished outputs are not restored. Regenerate them with the producing tool before publishing.',+ }+ : {}),+ artifacts: [...(staged.get(JSON.stringify(actor))?.values() ?? [])].map((artifact) => ({+ artifact_id: artifact.id,+ filename: artifact.filename,+ })),+ };+ }++ async function capture(+ agentId: string,+ context: SubagentExecutionContext | undefined,+ toolCallId: string,+ artifact: CapturedRunArtifact,+ codeExecutionContext?: RunArtifactDescriptor['codeExecutionContext'],+ ): Promise<boolean> {+ if (!manifest || !context) return false;+ const actor = actorFor(agentId, context);+ const key = JSON.stringify(actor);+ const incomingFiles = (artifact.files ?? []).filter((file) => file.inherited !== true);+ const operationSignal = codeSignals.get(key);+ const captureSignal = operationSignal+ ? AbortSignal.any([lifetime.signal, operationSignal])+ : lifetime.signal;+ const outputs = staged.get(key) ?? new Map<string, SharedRunArtifact>();+ staged.set(key, outputs);+ for (const file of incomingFiles) {+ const sessionId = file.storage_session_id ?? file.session_id ?? artifact.session_id;+ if (!sessionId) throw new Error('The generated artifact has no sandbox identity.');+ const source: RunArtifactDescriptor = {+ id: file.id,+ name: file.name,+ sessionId,+ codeExecutionContext,+ };+ const snapshot = await deps.snapshots.capture(source, captureSignal);+ let retained = false;+ try {+ captureSignal.throwIfAborted();+ // Reading an unchanged file must not consume another catalog entry. A+ // content comparison is required: providers may reuse IDs after a write.+ let latest: SharedRunArtifact | undefined;+ for (const output of outputs.values()) {+ if (output.filename === file.name) latest = output;+ }+ if (latest?.sha256 === snapshot.sha256) {+ continue;+ }+ const value: SharedRunArtifact = {+ id: `${randomUUID()}:${toolCallId}:${file.id}`,+ filename: file.name,+ sha256: snapshot.sha256,+ source: { ...source, snapshotId: snapshot.snapshotId },+ };+ manifest.stage(actor, value);+ outputs.set(value.id, value);+ retained = true;+ } finally {+ if (!retained) await deps.snapshots.discard(snapshot.snapshotId);+ }+ }+ return true;+ }++ function withCodeExecution<T>(+ agentId: string,+ context: SubagentExecutionContext | undefined,+ signal: AbortSignal,+ execute: () => Promise<T>,+ ): Promise<T> {+ if (!manifest) return execute();+ const key = JSON.stringify(actorFor(agentId, context));+ const previous = codeOperations.get(key) ?? Promise.resolve();+ const operation = previous.then(async () => {+ signal.throwIfAborted();+ lifetime.signal.throwIfAborted();+ codeSignals.set(key, signal);+ try {+ return await execute();+ } finally {+ codeSignals.delete(key);+ }+ });+ const settled = operation.then(+ () => undefined,+ () => undefined,+ );+ codeOperations.set(key, settled);+ void settled.then(() => {+ if (codeOperations.get(key) === settled) codeOperations.delete(key);+ });+ return operation;+ }++ async function publish(+ agentId: string,+ context: SubagentExecutionContext | undefined,+ artifactId: string,+ recipients: string[] = [],+ signal?: AbortSignal,+ ): Promise<TFile> {+ const actor = actorFor(agentId, context);+ const key = JSON.stringify(actor);+ const snapshotId = staged.get(key)?.get(artifactId)?.source.snapshotId;+ const publicationSignal = signal ? AbortSignal.any([lifetime.signal, signal]) : lifetime.signal;+ const file = await manifest!.publish(actor, artifactId, recipients, publicationSignal);+ staged.get(key)?.delete(artifactId);+ if (snapshotId) {+ try {+ await deps.snapshots.discard(snapshotId);+ } catch {+ // The durable publication already committed. A private cleanup failure+ // must not turn it into an apparent publish failure; close retries it.+ deps.audit?.({+ action: 'cleanup_failed',+ scope: scope!,+ executionId: actor.executionId,+ agentId,+ fileIds: [],+ });+ }+ }+ publicationSignal.throwIfAborted();+ const rootDispatch = context?.ancestry[0];+ await deps.emit({+ ...file,+ messageId: scope!.runId,+ toolCallId: rootDispatch?.parentToolCallId,+ agentId: rootDispatch?.parentAgentId ?? rootAgentId!,+ });+ return file;+ }++ async function complete(input: RunFilePreparation, result: { content: string }) {+ if (!manifest) return result;+ const memberFiles = await Promise.all(+ input.memberAgentIds.map((agentId) =>+ manifest!.getFiles(actorFor(agentId, input.executionContext), input.signal),+ ),+ );+ const ancestry = input.executionContext.ancestry;+ const executionId = ancestry[ancestry.length - 1]?.subagentRunId;+ const published = [+ ...new Map(+ memberFiles+ .flat()+ .filter((file) => file.metadata?.runFile?.executionId === executionId)+ .map((file) => [file.file_id, file]),+ ).values(),+ ];+ if (published.length === 0) return result;+ return {+ content: `${result.content}\n\nPublished files: ${JSON.stringify(published.map((file) => ({ file_id: file.file_id, filename: file.filename })))}`,+ };+ }++ async function prepareTools(+ agentId: string,+ context: SubagentExecutionContext | undefined,+ signal: AbortSignal,+ mode: RunFileReadMode = 'refresh',+ ) {+ if (!manifest) return;+ const actor = actorFor(agentId, context);+ const revision = nextPreparation(actor);+ await deps.prepareAgent({+ actor,+ files: await manifest.getFiles(actor, signal, mode),+ sessionKey: sessionKey(actor),+ revision,+ signal,+ });+ }++ function endRun(): void {+ void close();+ }++ function close(): Promise<void> {+ if (closing) return closing;+ clearTimeout(expiryTimer);+ runSignal?.removeEventListener('abort', endRun);+ lifetime.abort(new Error('This shared-file run has expired. Attach the file to a new turn.'));+ codeOperations.clear();+ codeSignals.clear();+ manifest?.close();+ staged.clear();+ contexts.clear();+ members.clear();+ preparations.clear();+ resumedExecutions.clear();+ closing = deps.snapshots.close().catch(() => {+ if (scope)+ deps.audit?.({ action: 'cleanup_failed', scope, executionId: scope.runId, fileIds: [] });+ });+ return closing;+ }++ return {+ activate,+ prepare,+ complete,+ list,+ capture,+ withCodeExecution,+ publish,+ prepareTools,+ actorFor,+ close,+ isActive: () => manifest != null,+ };+}diff --git a/packages/api/src/agents/files/snapshots.spec.ts b/packages/api/src/agents/files/snapshots.spec.tsnew file mode 100644index 0000000000..f0c0438ca5--- /dev/null+++ b/packages/api/src/agents/files/snapshots.spec.ts@@ -0,0 +1,206 @@+import { join } from 'node:path';+import { createHash } from 'node:crypto';+import { promises as fs } from 'node:fs';+import { PassThrough, Readable } from 'node:stream';+import type { RunArtifactDescriptor } from '~/files/code/publication';+import type { RunFileSnapshotStore } from './snapshots';+import { createRunFileSnapshotStore } from './snapshots';++const source: RunArtifactDescriptor = {+ id: 'source-object',+ name: '../../report.csv',+ sessionId: 'sandbox-storage',+};++function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++describe('createRunFileSnapshotStore', () => {+ const stores: RunFileSnapshotStore[] = [];++ function create(options: Parameters<typeof createRunFileSnapshotStore>[0]): RunFileSnapshotStore {+ const store = createRunFileSnapshotStore(options);+ stores.push(store);+ return store;+ }++ afterEach(async () => {+ await Promise.all(stores.splice(0).map((store) => store.close()));+ jest.restoreAllMocks();+ });++ it('retains immutable bytes and hashes without exposing source names as local paths', async () => {+ const mkdir = jest.spyOn(fs, 'mkdtemp');+ let content = 'original';+ const store = create({+ open: async () => Readable.from([Buffer.from(content)]),+ maxBytes: 32,+ maxFiles: 3,+ });+ const first = await store.capture(source);+ content = 'changed';+ const second = await store.capture(source);++ expect(first).toEqual({+ snapshotId: expect.any(String),+ size: 8,+ sha256: createHash('sha256').update('original').digest('hex'),+ });+ expect(second.snapshotId).not.toBe(first.snapshotId);+ expect(second.sha256).not.toBe(first.sha256);+ const read = await store.read(first.snapshotId);+ expect(read.toString()).toBe('original');+ read.fill(0);+ expect((await store.read(first.snapshotId)).toString()).toBe('original');+ expect((await store.read(second.snapshotId)).toString()).toBe('changed');++ const directory: string = await mkdir.mock.results[0].value;+ expect((await fs.readdir(directory)).sort()).toEqual(+ [first.snapshotId, second.snapshotId].sort(),+ );+ if (process.platform !== 'win32') {+ expect((await fs.stat(directory)).mode & 0o777).toBe(0o700);+ expect((await fs.stat(join(directory, first.snapshotId))).mode & 0o777).toBe(0o600);+ }+ await store.close();+ await expect(fs.stat(directory)).rejects.toMatchObject({ code: 'ENOENT' });+ });++ it('reserves file slots before opening parallel sources', async () => {+ const opening = deferred<Readable>();+ const started = deferred<void>();+ let firstOpen = true;+ const open = jest.fn(async () => {+ if (!firstOpen) return Readable.from(['bytes']);+ firstOpen = false;+ started.resolve(undefined);+ return opening.promise;+ });+ const store = create({ open, maxBytes: 32, maxFiles: 1 });+ const first = store.capture(source);+ await started.promise;+ await expect(store.capture(source)).rejects.toThrow('file limit');+ expect(open).toHaveBeenCalledTimes(1);+ opening.resolve(Readable.from(['bytes']));+ const captured = await first;+ await store.discard(captured.snapshotId);+ await store.discard(captured.snapshotId);+ await expect(store.capture(source)).resolves.toMatchObject({ size: 5 });+ });++ it('shares one byte budget across parallel children and frees rejected partial writes', async () => {+ const store = create({+ open: async (artifact) => Readable.from([Buffer.from(artifact.name)]),+ maxBytes: 6,+ maxFiles: 3,+ });+ const results = await Promise.allSettled([+ store.capture({ ...source, name: 'abcd' }),+ store.capture({ ...source, name: 'efgh' }),+ ]);+ const successful = results.filter((result) => result.status === 'fulfilled');+ expect(successful).toHaveLength(1);+ expect(results.filter((result) => result.status === 'rejected')).toHaveLength(1);+ await expect(store.capture({ ...source, name: '12' })).resolves.toMatchObject({ size: 2 });+ await expect(store.capture({ ...source, name: 'x' })).rejects.toThrow('byte limit');+ });++ it('removes a failed stream and releases its disk and accounting reservations', async () => {+ const mkdir = jest.spyOn(fs, 'mkdtemp');+ let fail = true;+ const store = create({+ open: async () =>+ Readable.from(+ (async function* () {+ yield Buffer.from('abcdef');+ if (fail) throw new Error('upstream stopped');+ })(),+ ),+ maxBytes: 6,+ maxFiles: 1,+ });+ await expect(store.capture(source)).rejects.toThrow('upstream stopped');+ const directory: string = await mkdir.mock.results[0].value;+ expect(await fs.readdir(directory)).toEqual([]);+ fail = false;+ await expect(store.capture(source)).resolves.toMatchObject({ size: 6 });+ });++ it('cancels a streaming capture and permits a later capture within the same budget', async () => {+ const streaming = new PassThrough();+ const started = deferred<void>();+ let first = true;+ const store = create({+ open: async () => {+ if (!first) return Readable.from(['complete']);+ first = false;+ started.resolve(undefined);+ return streaming;+ },+ maxBytes: 8,+ maxFiles: 1,+ });+ const controller = new AbortController();+ const capturing = store.capture(source, controller.signal);+ await Promise.all([+ expect(capturing).rejects.toThrow(),+ (async () => {+ await started.promise;+ streaming.write('part');+ await new Promise<void>((resolve) => setImmediate(resolve));+ controller.abort(new Error('cancelled'));+ })(),+ ]);+ expect(streaming.destroyed).toBe(true);+ await expect(store.capture(source)).resolves.toMatchObject({ size: 8 });+ });++ it('closes without waiting for an uncooperative opener and destroys its late stream', async () => {+ const mkdir = jest.spyOn(fs, 'mkdtemp');+ const opening = deferred<Readable>();+ const started = deferred<void>();+ const store = create({+ open: async () => {+ started.resolve(undefined);+ return opening.promise;+ },+ maxBytes: 8,+ maxFiles: 1,+ });+ const capturing = store.capture(source);+ await Promise.all([+ expect(capturing).rejects.toThrow('closed'),+ (async () => {+ await started.promise;+ await store.close();+ })(),+ ]);+ const directory: string = await mkdir.mock.results[0].value;+ await expect(fs.stat(directory)).rejects.toMatchObject({ code: 'ENOENT' });+ const late = new PassThrough();+ opening.resolve(late);+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(late.destroyed).toBe(true);+ await expect(store.capture(source)).rejects.toThrow('closed');+ await expect(store.read('anything')).rejects.toThrow('closed');+ await store.close();+ });++ it('rejects unknown or discarded IDs without treating them as filesystem paths', async () => {+ const store = create({+ open: async () => Readable.from(['bytes']),+ maxBytes: 8,+ maxFiles: 1,+ });+ const snapshot = await store.capture(source);+ await store.discard(snapshot.snapshotId);+ await expect(store.read(snapshot.snapshotId)).rejects.toThrow('unavailable');+ await expect(store.read('../../report.csv')).rejects.toThrow('unavailable');+ await store.discard('../../report.csv');+ });+});diff --git a/packages/api/src/agents/files/snapshots.ts b/packages/api/src/agents/files/snapshots.tsnew file mode 100644index 0000000000..4d744e3960--- /dev/null+++ b/packages/api/src/agents/files/snapshots.ts@@ -0,0 +1,243 @@+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { Transform } from 'node:stream';+import { pipeline } from 'node:stream/promises';+import { createHash, randomUUID } from 'node:crypto';+import { createWriteStream, promises as fs } from 'node:fs';+import type { Readable, TransformCallback } from 'node:stream';+import type { RunArtifactDescriptor } from '~/files/code/publication';++export interface RunFileSnapshot {+ snapshotId: string;+ size: number;+ sha256: string;+}++export interface RunFileSnapshotStore {+ capture: (source: RunArtifactDescriptor, signal?: AbortSignal) => Promise<RunFileSnapshot>;+ read: (snapshotId: string, signal?: AbortSignal) => Promise<Buffer>;+ discard: (snapshotId: string) => Promise<void>;+ close: () => Promise<void>;+}++interface SnapshotEntry {+ snapshotId: string;+ size: number;+ ready: boolean;+ path?: string;+ controller: AbortController;+ reads: Set<Promise<Buffer>>;+ removal?: Promise<void>;+}++/** Keeps immutable private bytes off the heap and outside the public file store. */+export function createRunFileSnapshotStore({+ open,+ maxBytes,+ maxFiles,+}: {+ open: (source: RunArtifactDescriptor, signal?: AbortSignal) => Promise<Readable>;+ /** Aggregate bytes reserved by completed and currently streaming snapshots. */+ maxBytes: number;+ /** Includes captures that have not yet finished opening their source. */+ maxFiles: number;+}): RunFileSnapshotStore {+ if (+ !Number.isSafeInteger(maxBytes) ||+ maxBytes < 1 ||+ !Number.isSafeInteger(maxFiles) ||+ maxFiles < 1+ ) {+ throw new Error('Private artifact snapshot limits must be positive safe integers.');+ }++ const entries = new Map<string, SnapshotEntry>();+ const operations = new Set<Promise<unknown>>();+ const lifetime = new AbortController();+ let directory: Promise<string> | undefined;+ let allocatedBytes = 0;+ let closed = false;+ let closing: Promise<void> | undefined;++ function assertOpen(signal?: AbortSignal): void {+ signal?.throwIfAborted();+ if (closed) throw new Error('Private artifact snapshots are closed.');+ }++ function track<T>(operation: Promise<T>): Promise<T> {+ operations.add(operation);+ const release = (): void => {+ operations.delete(operation);+ };+ void operation.then(release, release);+ return operation;+ }++ function getDirectory(): Promise<string> {+ directory ??= (async () => {+ const created = await fs.mkdtemp(join(tmpdir(), 'librechat-run-files-'));+ try {+ await fs.chmod(created, 0o700);+ return created;+ } catch (error) {+ await fs.rm(created, { recursive: true, force: true });+ throw error;+ }+ })();+ return directory;+ }++ function openSource(source: RunArtifactDescriptor, signal: AbortSignal): Promise<Readable> {+ return new Promise<Readable>((resolve, reject) => {+ const aborted = (): void => reject(signal.reason);+ signal.addEventListener('abort', aborted, { once: true });+ Promise.resolve()+ .then(() => {+ signal.throwIfAborted();+ return open(source, signal);+ })+ .then(+ (stream) => {+ signal.removeEventListener('abort', aborted);+ // An adapter may resolve after cancellation even when passed a signal.+ // Do not let that late source keep a socket or start another disk write.+ if (signal.aborted) {+ stream.destroy();+ reject(signal.reason);+ return;+ }+ resolve(stream);+ },+ (error: unknown) => {+ signal.removeEventListener('abort', aborted);+ reject(error);+ },+ );+ });+ }++ function remove(entry: SnapshotEntry): Promise<void> {+ if (entry.removal) return entry.removal;+ entry.ready = false;+ entry.controller.abort(new Error('The private artifact snapshot was discarded.'));+ const removal = (async () => {+ await Promise.allSettled([...entry.reads]);+ if (entry.path) await fs.rm(entry.path, { force: true });+ if (entries.get(entry.snapshotId) === entry) {+ entries.delete(entry.snapshotId);+ allocatedBytes -= entry.size;+ }+ })();+ entry.removal = removal;+ void removal.catch(() => {+ // A later close can retry cleanup after a transient filesystem failure.+ if (entry.removal === removal) entry.removal = undefined;+ });+ return removal;+ }++ function capture(source: RunArtifactDescriptor, signal?: AbortSignal): Promise<RunFileSnapshot> {+ return track(+ (async () => {+ assertOpen(signal);+ if (entries.size >= maxFiles) {+ throw new Error('The private artifact snapshot file limit has been reached.');+ }+ const entry: SnapshotEntry = {+ snapshotId: randomUUID(),+ size: 0,+ ready: false,+ controller: new AbortController(),+ reads: new Set(),+ };+ entries.set(entry.snapshotId, entry);+ const effectiveSignal = AbortSignal.any([+ lifetime.signal,+ entry.controller.signal,+ ...(signal ? [signal] : []),+ ]);+ try {+ const root = await getDirectory();+ effectiveSignal.throwIfAborted();+ const stream = await openSource(source, effectiveSignal);+ entry.path = join(root, entry.snapshotId);+ const hash = createHash('sha256');+ const counter = new Transform({+ transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback): void {+ if (chunk.byteLength > maxBytes - allocatedBytes) {+ callback(new Error('The private artifact snapshot byte limit has been reached.'));+ return;+ }+ // No await between the check and reservation: concurrent child streams+ // consume one shared budget, including writes still in progress.+ allocatedBytes += chunk.byteLength;+ entry.size += chunk.byteLength;+ hash.update(chunk);+ callback(null, chunk);+ },+ });+ await pipeline(+ stream,+ counter,+ createWriteStream(entry.path, { flags: 'wx', mode: 0o600 }),+ { signal: effectiveSignal },+ );+ effectiveSignal.throwIfAborted();+ entry.ready = true;+ return { snapshotId: entry.snapshotId, size: entry.size, sha256: hash.digest('hex') };+ } catch (error) {+ await remove(entry);+ throw error;+ }+ })(),+ );+ }++ function read(snapshotId: string, signal?: AbortSignal): Promise<Buffer> {+ return track(+ (async () => {+ assertOpen(signal);+ const entry = entries.get(snapshotId);+ if (!entry?.ready || !entry.path) {+ throw new Error('The private artifact snapshot is unavailable.');+ }+ const effectiveSignal = AbortSignal.any([+ lifetime.signal,+ entry.controller.signal,+ ...(signal ? [signal] : []),+ ]);+ const reading = fs.readFile(entry.path, { signal: effectiveSignal });+ entry.reads.add(reading);+ try {+ const buffer = await reading;+ effectiveSignal.throwIfAborted();+ return buffer;+ } finally {+ entry.reads.delete(reading);+ }+ })(),+ );+ }++ function discard(snapshotId: string): Promise<void> {+ const entry = entries.get(snapshotId);+ return entry ? track(remove(entry)) : Promise.resolve();+ }++ function close(): Promise<void> {+ if (closing) return closing;+ closed = true;+ lifetime.abort(new Error('Private artifact snapshots are closed.'));+ closing = (async () => {+ await Promise.allSettled([...operations]);+ await Promise.allSettled([...entries.values()].map(remove));+ const root = await directory?.catch(() => undefined);+ if (root) await fs.rm(root, { recursive: true, force: true });+ entries.clear();+ allocatedBytes = 0;+ })();+ return closing;+ }++ return { capture, read, discard, close };+}diff --git a/packages/api/src/agents/handlers.spec.ts b/packages/api/src/agents/handlers.spec.tsindex 4b75a67a23..c65b82c91e 100644--- a/packages/api/src/agents/handlers.spec.ts+++ b/packages/api/src/agents/handlers.spec.ts@@ -446,6 +446,7 @@ describe('createToolExecuteHandler', () => {undefined,undefined,controller.signal,+ undefined,);});@@ -895,6 +896,7 @@ describe('createToolExecuteHandler', () => {configurable,undefined,undefined,+ undefined,);expect(JSON.stringify(jest.mocked(loadTools).mock.calls)).not.toContain(protectedName);expect(results[0]).toEqual(@@ -1426,6 +1428,7 @@ describe('createToolExecuteHandler', () => {undefined,callerCapabilityProjection,undefined,+ undefined,);expect(capturedConfigs[0].toolDefs).toEqual([{ name: 'active_programmatic_tool', allowed_callers: ['code_execution'] },diff --git a/packages/api/src/agents/handlers.ts b/packages/api/src/agents/handlers.tsindex 4aad6c0789..e3f518d788 100644--- a/packages/api/src/agents/handlers.ts+++ b/packages/api/src/agents/handlers.ts@@ -17,6 +17,7 @@ import type {ToolExecuteResult,ToolExecuteBatchRequest,SubagentTaskConfig,+ SubagentExecutionContext,CallerCapabilityProjectionSnapshot,StreamEventData,ToolEndCallback as SdkToolEndCallback,@@ -43,6 +44,7 @@ import type { ArtifactDeliveryFailure } from '~/files/code';import type { BackgroundToolResultState } from './harvest';import type { CodeExecutionContext } from './execution';import type { TextContentFragment } from '~/protection';+import type { RunFileSession } from './files/session';import type { ServerRequest } from '~/types';import {backgroundTaskRegistry,@@ -80,7 +82,9 @@ import {HOST_FILE_AUTHORING_ARTIFACT_KEY,LIST_WORKSPACE_FILES_TOOL_NAME,SEARCH_WORKSPACE_TOOL_NAME,+ isCodeFileToolName,isCodeSessionToolName,+ isFileResourceToolName,} from './tools';import {createCodeApiRateLimitBudget,@@ -186,6 +190,8 @@ export interface EventActorDetachedActionLifecycle {}export interface ToolEndCallbackMetadata {+ /** SDK-authored lineage for artifacts generated inside a child execution. */+ executionContext?: SubagentExecutionContext;run_id?: string;thread_id?: string;[key: string]: unknown;@@ -244,6 +250,8 @@ export interface ToolExecuteOptions {callerCapabilityProjection?: CallerCapabilityProjectionSnapshot,/** Effective cancellation signal for this tool-execute batch. */signal?: AbortSignal,+ /** SDK-authored lineage; never derive child identity from saved agent IDs. */+ executionContext?: SubagentExecutionContext,) => Promise<{loadedTools: StructuredToolInterface[];/** Additional configurable properties to merge (e.g., userMCPAuthMap) */@@ -251,6 +259,8 @@ export interface ToolExecuteOptions {}>;/** Trusted detached-subagent task scope for polling and parent controls. */subagentTasks?: SubagentTaskConfig;+ /** Shared-file grants and tool contexts scoped to the executing run instance. */+ runFiles?: Pick<RunFileSession, 'isActive' | 'prepareTools' | 'withCodeExecution'>;/** Trusted deployment gate for cooperative ordinary-tool cancellation. */ordinaryToolCancellation?: boolean;/** Callback to process tool artifacts (code output files, file citations, etc.) */@@ -264,6 +274,7 @@ export interface ToolExecuteOptions {toolNames: string[],agentId?: string,signal?: AbortSignal,+ executionContext?: SubagentExecutionContext,) => Promise<CodeEnvFile[] | void>;/*** Persists a backgrounded code-execution result onto the dispatch turn once@@ -5246,6 +5257,7 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHandemitAttachment,emitPtcProgress,subagentTasks,+ runFiles,ordinaryToolCancellation = false,provisionFiles,} = options;@@ -5255,12 +5267,23 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHandconst {toolCalls,agentId,- configurable,- metadata,+ configurable: incomingConfigurable,+ metadata: incomingMetadata,signal: eventRunSignal,resolve,reject,} = data;+ const executionContext = (+ data as ToolExecuteBatchRequest & { executionContext?: SubagentExecutionContext }+ ).executionContext;+ // Only the SDK-owned batch field may establish a child execution. Runtime+ // configurable and callback metadata can otherwise carry inherited values.+ const configurable: Record<string, unknown> | undefined =+ incomingConfigurable == null ? undefined : { ...incomingConfigurable, executionContext };+ const metadata: Record<string, unknown> | undefined =+ incomingMetadata == null && executionContext == null+ ? undefined+ : { ...incomingMetadata, executionContext };let eventRunId: string | undefined;if (typeof metadata?.run_id === 'string') {eventRunId = metadata.run_id;@@ -5329,8 +5352,18 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand}const toolNames = [...new Set(allowedToolCalls.map((tc) => tc.name))];+ const runFileSharingActive = runFiles?.isActive() === true;+ if (runFileSharingActive) {+ if (!agentId) throw new Error('Shared-file tools require an executing agent.');+ await runFiles!.prepareTools(+ agentId,+ executionContext,+ runSignal ?? new AbortController().signal,+ toolNames.some(isFileResourceToolName) ? 'refresh' : 'snapshot',+ );+ }const provisionedCodeFiles = provisionFiles- ? await provisionFiles(toolNames, agentId, runSignal)+ ? await provisionFiles(toolNames, agentId, runSignal, executionContext): undefined;const { loadedTools, configurable: toolConfigurable } = await loadTools(@@ -5339,6 +5372,7 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHandsourceConfigurable,callerCapabilityProjection,runSignal,+ executionContext,);const toolMap = new Map(loadedTools.map((t) => [t.name, t]));const loadedConfigurable = toolConfigurable as Record<string, unknown> | undefined;@@ -5346,6 +5380,7 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHandsourceConfigurable,loadedConfigurable,);+ if (mergedConfigurable != null) mergedConfigurable.executionContext = executionContext;/* The graph populated each call's code-session context from the sessions that* existed at run start, before this batch provisioned anything, and nothing* downstream refreshes it. buildToolCallConfig reads `_injected_files` from@@ -5353,7 +5388,10 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand* a sandbox that cannot see the file. */if (provisionedCodeFiles && provisionedCodeFiles.length > 0) {for (const tc of allowedToolCalls) {- if (!isCodeSessionAwareToolCall(tc.name, mergedConfigurable)) {+ if (+ !isCodeSessionAwareToolCall(tc.name, mergedConfigurable) &&+ !(runFileSharingActive && isCodeFileToolName(tc.name))+ ) {continue;}const merged = mergeCodeFilesIntoContext(@@ -5368,6 +5406,21 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHandconst codeExecutionContext = getCodeExecutionContext(mergedConfigurable);const runtimeSessionHint = codeExecutionContext?.runtimeSessionHint;+ if (runFileSharingActive && executionContext != null) {+ for (const tc of allowedToolCalls) {+ if (+ !isCodeSessionAwareToolCall(tc.name, mergedConfigurable) &&+ !isCodeFileToolName(tc.name)+ )+ continue;+ if (!runtimeSessionHint || codeExecutionContext?.environmentType === 'attached') {+ throw new Error('This child execution has no isolated file workspace.');+ }+ // SDK tool configs may still carry a parent's runtime hint. The+ // host prepared this partition using the authorized child identity.+ tc.runtimeSessionHint = runtimeSessionHint;+ }+ }const executionRouteKey =codeExecutionContext?.executionRouteKey ?? codeExecutionContext?.executionProfile;const sandboxConversationId =@@ -6469,6 +6522,15 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand});}+ const usesCodeFiles =+ isCodeFileToolName(tc.name) ||+ isCodeSessionAwareToolCall(tc.name, mergedConfigurable);+ if (runFileSharingActive && usesCodeFiles && isBackgroundRequested(tc.args)) {+ return reportResult(+ errorResult(tc, 'Shared-file code tools require foreground execution.'),+ );+ }+if (backgroundToolSet.has(tc.name) &&isBackgroundRequested(tc.args) &&@@ -7019,9 +7081,18 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand}};+ const executeWithFileScope = (sandboxContext?: SandboxSessionContext) =>+ runFileSharingActive && usesCodeFiles && runFiles != null && agentId != null+ ? runFiles.withCodeExecution(+ agentId,+ executionContext,+ runSignal ?? new AbortController().signal,+ () => execute(sandboxContext),+ )+ : execute(sandboxContext);const queueKey = getFileAuthoringQueueKey(tc, mergedConfigurable);if (!queueKey) {- return reportResult(await execute());+ return reportResult(await executeWithFileScope());}let sandboxContext: SandboxSessionContext | undefined;if (queueKey.startsWith('sandbox:')) {@@ -7032,8 +7103,8 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand}const previous = authoringQueues.get(queueKey) ?? Promise.resolve();const resultPromise = previous.then(- () => execute(sandboxContext),- () => execute(sandboxContext),+ () => executeWithFileScope(sandboxContext),+ () => executeWithFileScope(sandboxContext),);authoringQueues.set(queueKey,diff --git a/packages/api/src/agents/index.ts b/packages/api/src/agents/index.tsindex 53c81e15ea..37d3042614 100644--- a/packages/api/src/agents/index.ts+++ b/packages/api/src/agents/index.ts@@ -84,3 +84,4 @@ export * from './toolValidation';export * from './remote';export * from './queuedTurns';export * from './queuedTurnHttp';+export * from './files/index';diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.tsindex 5b2dd0f0ac..8f754dc79f 100644--- a/packages/api/src/agents/initialize.ts+++ b/packages/api/src/agents/initialize.ts@@ -475,8 +475,10 @@ export type InitializedAgent = Agent & {tools: GenericTool[];/** @deprecated use requestAttachments or agentContextAttachments based on sharing semantics. */attachments: IMongoFile[];- /** Files attached to the current user message/run and safe to share across run agents. */+ /** Message files admitted for this agent, including historical files when resend is enabled. */requestAttachments: IMongoFile[];+ /** Only hydrated attachments from the current request; excludes history and agent setup files. */+ currentRequestAttachments: TFile[];/** Files attached to this agent's permanent context via tool_resources. */agentContextAttachments: IMongoFile[];toolContextMap: Record<string, unknown>;@@ -652,6 +654,8 @@ export interface InitializeAgentParams {requestBody?: RequestBody;/** Request files */requestFiles?: IMongoFile[];+ /** Host-authorized, hydrated inputs for an isolated execution. Suppresses parent history reads. */+ authorizedRunFiles?: readonly TFile[];/** Function to load agent tools */loadTools?: (params: {provider: string;@@ -873,6 +877,7 @@ export async function initializeAgent(agent,loadTools,requestFiles = [],+ authorizedRunFiles,conversationId,endpointOption,parentMessageId,@@ -1091,7 +1096,7 @@ export async function initializeAgent();}- let currentFiles: IMongoFile[] | undefined;+ let currentFiles: Array<IMongoFile | TFile> | undefined;const _modelOptions = structuredClone(Object.assign(@@ -1182,7 +1187,11 @@ export async function initializeAgent(const wantsSearchFiles = toolResourceSet.has(EToolResources.file_search);const wantsProvisioning = wantsCodeFiles || wantsSearchFiles;- if (conversationId != null && (resendFiles || wantsProvisioning)) {+ if (+ authorizedRunFiles === undefined &&+ conversationId != null &&+ (resendFiles || wantsProvisioning)+ ) {const getThreadMessages = db.getMessages;/** Falsy anchors cannot match a parent chain, so they get no walk. */const threadAnchor =@@ -1317,7 +1326,7 @@ export async function initializeAgent(const snapshotFileIds = [...requestFileIds, ...toolFileIds, ...deferredProvisionFileIds];let requestUsageFiles: IMongoFile[] = [];let toolUsageFiles: IMongoFile[] = [];- if (requestFileOwnerScope && snapshotFileIds.length > 0) {+ if (authorizedRunFiles === undefined && requestFileOwnerScope && snapshotFileIds.length > 0) {const hydratedFiles =((await db.getFiles({@@ -1345,7 +1354,17 @@ export async function initializeAgent(.map((fileId) => hydratedFilesById.get(fileId)).filter((file): file is IMongoFile => file != null);}- if (requestFiles.length > 0 || toolFileIds.length > 0) {+ if (authorizedRunFiles !== undefined) {+ for (const file of authorizedRunFiles) {+ if (+ file.user !== requestFileOwnerId ||+ (file.tenantId ?? null) !== (user?.tenantId ?? null)+ ) {+ throw new Error('Run file inputs do not match the authenticated owner');+ }+ }+ currentFiles = authorizedRunFiles.map((file) => structuredClone(file));+ } else if (requestFiles.length > 0 || toolFileIds.length > 0) {currentFiles = requestUsageFiles.concat(toolUsageFiles);}@@ -1363,7 +1382,9 @@ export async function initializeAgent(skipTotalSizeLimit: true,preserveTextSources: true,});- const requestUsageFileIds = new Set(requestUsageFiles.map((file) => file.file_id));+ const requestUsageFileIds = new Set(+ (authorizedRunFiles ?? requestUsageFiles).map((file) => file.file_id),+ );assertAgentAttachmentLimits({attachments: currentFiles.filter((file) => requestUsageFileIds.has(file.file_id) && isModelBoundAttachmentFile(file),@@ -1468,7 +1489,7 @@ export async function initializeAgent(? (Promise.resolve(currentFiles) as unknown as Promise<TFile[]>): undefined,tool_resources: agent.tool_resources,- requestFileSet: new Set(requestFiles?.map((file) => file.file_id)),+ requestFileSet: new Set((authorizedRunFiles ?? requestFiles).map((file) => file.file_id)),enabledToolResources: toolResourceSet,checkSessionsAlive: db.checkSessionsAlive,loadCodeApiKey: db.loadCodeApiKey,@@ -2105,6 +2126,14 @@ export async function initializeAgent(const finalAttachments: IMongoFile[] = toMongoFiles(primedAttachments);const requestAttachments: IMongoFile[] = toMongoFiles(primedRequestAttachments);const agentContextAttachments: IMongoFile[] = toMongoFiles(primedAgentContextAttachments);+ const currentRequestFileIds = new Set(requestFileIds);+ const currentRequestAttachments: TFile[] = (primedRequestAttachments ?? [])+ .filter((file): file is TFile => file != null && currentRequestFileIds.has(file.file_id))+ .map((file) => ({+ ...file,+ user: String(file.user),+ ...(file._id == null ? {} : { _id: String(file._id) }),+ }));const compatibilityAttachments =finalAttachments.length > 0@@ -2165,6 +2194,7 @@ export async function initializeAgent(alwaysApplySkillPrimes,attachments: compatibilityAttachments,requestAttachments,+ currentRequestAttachments,agentContextAttachments,toolContextMap: toolContextMap ?? {},dynamicToolContextMap: dynamicToolContextMap ?? {},diff --git a/packages/api/src/agents/openai/service.spec.ts b/packages/api/src/agents/openai/service.spec.tsindex b9aa611fa5..8ecde5caa0 100644--- a/packages/api/src/agents/openai/service.spec.ts+++ b/packages/api/src/agents/openai/service.spec.ts@@ -256,6 +256,7 @@ describe('createAgentChatCompletion - MCP permission user propagation', () => {expect.objectContaining({ requestBody: runArgs.requestBody }),undefined,processStream.mock.calls[0][1].signal,+ undefined,);expect(loadTools.mock.calls[0][4]).toBeInstanceOf(AbortSignal);await runArgs.customHandlers[GraphEvents.ON_TOOL_EXECUTE].handle(GraphEvents.ON_TOOL_EXECUTE, {diff --git a/packages/api/src/agents/run.ts b/packages/api/src/agents/run.tsindex 33ef49468a..21fb29c03a 100644--- a/packages/api/src/agents/run.ts+++ b/packages/api/src/agents/run.ts@@ -11,6 +11,7 @@ import {extractEnvVariable,providerEndpointMap,normalizeEndpointName,+ resolveUseResponsesApi,} from 'librechat-data-provider';import type {SummarizationConfig as AgentSummarizationConfig,@@ -35,6 +36,7 @@ import type {} from '@librechat/agents';import type {Agent,+ ImageDetail,CodeApprovalMode,TAgentsEndpoint,AgentModelParameters,@@ -56,6 +58,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 { RunFileSession } from './files/session';import type { RunFadingTiers } from './fading';import type * as t from '~/types';import {@@ -90,6 +93,11 @@ import {ASK_USER_QUESTION_TOOL_NAME,createAskUserQuestionTool,} from '~/agents/hitl/askUserQuestionTool';+import {+ createRunFileTools,+ eventOnlyRunFileTools,+ isRunFileSharingSupported,+} from './files/runtime';import {resolveStreamLimits,resolveSubagentMaxTurns,@@ -409,6 +417,7 @@ type RunAgent = Omit<Agent, 'tools'> & {/** Pre-ratio context budget from initializeAgent. */baseContextTokens?: number;useLegacyContent?: boolean;+ imageDetail?: ImageDetail;toolContextMap?: Record<string, unknown>;dynamicToolContextMap?: Record<string, unknown>;toolRegistry?: LCToolRegistry;@@ -1573,6 +1582,7 @@ export async function createRun({appConfig,subagentUsageSink,subagentTasks,+ runFiles,steering,activityLabel,activityPhase,@@ -1664,6 +1674,8 @@ export async function createRun({subagentUsageSink?: (event: SubagentUsageEvent) => void;/** Host-owned detached-subagent task store and trusted parent-thread scope. */subagentTasks?: SubagentTaskConfig;+ /** Run-scoped file authorization and child context, supplied by the host. */+ runFiles?: RunFileSession;/*** The run-scoped steer-drain hook (a `PostToolBatch` callback built via* `createSteerDrainHook`). Registered on the run's hook registry independent@@ -1724,6 +1736,28 @@ export async function createRun({RunConfig,'tokenCounter' | 'customHandlers' | 'indexTokenCountMap' | 'initialSessions'>): Promise<Run<IState>> {+ const resolvedRunId = runId ?? randomUUID();+ const runFilesActive =+ runFiles?.activate(+ resolvedRunId,+ conversationId ?? requestBody?.conversationId ?? '',+ agents.map((agent) => agent.id),+ signal,+ ) === true;+ if (+ appConfig?.endpoints?.agents?.fileSharing?.enabled === true &&+ agents[0]?.subagents?.enabled === true &&+ agents[0]?.subagents?.shareFiles === true &&+ !runFilesActive+ ) {+ throw new Error('Run file sharing is not supported by this endpoint: a file host is required.');+ }+ if (runFilesActive && !isRunFileSharingSupported()) {+ throw new Error('Run file sharing requires an agents SDK with subagent context support.');+ }+ // Detached child threads resume in a new host request without this run's+ // input snapshot or publication routing. Shared children stay foreground.+ const activeSubagentTasks = runFilesActive ? undefined : subagentTasks;/*** Only extract discovered tools if:* 1. We have message history to parse@@ -1756,6 +1790,27 @@ export async function createRun({const buildAgentInput = (agent: RunAgent, opts: { isSubagent?: boolean } = {}): AgentInputs => {const isSubagent = opts.isSubagent === true;+ if (runFilesActive) {+ for (const { memberConfigs } of agent.subagentGraphConfigs ?? []) {+ const deliveryTargets = new Set(+ memberConfigs.map((member) =>+ JSON.stringify([+ member.provider,+ member.endpoint ?? member.provider,+ member.model_parameters?.model ?? member.model,+ resolveUseResponsesApi(member.model_parameters?.useResponsesApi) === true,+ // Unset detail inherits the request value, which may differ from explicit auto.+ member.imageDetail ?? null,+ ]),+ ),+ );+ if (deliveryTargets.size > 1) {+ throw new Error(+ 'Shared-file subagent teams must use the same provider, endpoint, model, API mode, and image-detail setting for every member.',+ );+ }+ }+ }const provider =(providerEndpointMap[agent.provider as keyof typeof providerEndpointMap@@ -1908,7 +1963,7 @@ export async function createRun({* admin-disabled) it is stripped fail-closed with no replacement.*/let tools = agent.tools;- let askGraphTools: GenericTool[] | undefined;+ let graphTools: GenericTool[] | undefined;if (agentRequestsAskUserQuestion(agent)) {tools = tools?.filter((tool) => (tool as { name?: string } | undefined)?.name !== ASK_USER_QUESTION_TOOL_NAME,@@ -1919,12 +1974,16 @@ export async function createRun({toolRegistry.delete(ASK_USER_QUESTION_TOOL_NAME);}if (hitlCapable && !isSubagent && !askToolAdminDisabled) {- askGraphTools = [+ graphTools = [createAskUserQuestionTool(toolInputValidationErrors) as unknown as GenericTool,];}}+ if (runFilesActive) {+ tools = eventOnlyRunFileTools(tools, toolDefinitions);+ }+const effectiveMaxContextTokens = computeEffectiveMaxContextTokens(summarization.reserveRatio,agent.baseContextTokens,@@ -1971,14 +2030,17 @@ export async function createRun({initialSessions: buildAgentInitialToolSessions(agent, initialSessions),codeSessionKey: agent.codeSessionKey,};- if (askGraphTools) {+ if (runFilesActive && runFiles != null && (isSubagent || agent.subagents?.enabled === true)) {+ graphTools = [...(graphTools ?? []), ...createRunFileTools(runFiles, agent.id, signal)];+ }+ if (graphTools) {/*** Typed structurally — not as `AgentInputs['graphTools']` — because the* field ships in `@librechat/agents` > 3.2.57 (agents#289); older SDK* versions ignore it at runtime (the tool is then simply absent, never* broken). Inline the field in the literal once the dependency is bumped.*/- (agentInput as AgentInputs & { graphTools?: GenericTool[] }).graphTools = askGraphTools;+ (agentInput as AgentInputs & { graphTools?: GenericTool[] }).graphTools = graphTools;}return agentInput;};@@ -2040,7 +2102,7 @@ export async function createRun({undefined,0,prebuiltGraphInputs,- subagentTasks != null,+ activeSubagentTasks != null,(resolvedAgent) => registerResolvedMCPToolAliases(resolvedAgent),);if (subagentConfigs.length > 0) {@@ -2048,11 +2110,14 @@ export async function createRun({/** Seed the SDK countdown that bounds nested delegation across isolated child graphs. */agentInput.maxSubagentDepth = MAX_SUBAGENT_DEPTH;}- if (subagentTasks != null) {+ if (activeSubagentTasks != null) {agentInput.toolDefinitions = registerBackgroundTaskTool({toolRegistry: agentInput.toolRegistry,toolDefinitions: agentInput.toolDefinitions,- subagentCompletionWakeups: agentUsesSubagentCompletionWakeups(subagentTasks, agent.id),+ subagentCompletionWakeups: agentUsesSubagentCompletionWakeups(+ activeSubagentTasks,+ agent.id,+ ),}).toolDefinitions;}agentInputs.push(agentInput);@@ -2214,13 +2279,13 @@ export async function createRun({* this guard is defense in depth).*/let hooks = hitl?.hooks;- if (usesSubagentCompletionWakeups(subagentTasks)) {+ if (usesSubagentCompletionWakeups(activeSubagentTasks)) {hooks = hooks ?? new HookRegistry();hooks.register('PostToolUse', {pattern: String(Constants.SUBAGENT),hooks: [createSubagentWakeupHandleHook((agentId) =>- agentUsesSubagentCompletionWakeups(subagentTasks, agentId),+ agentUsesSubagentCompletionWakeups(activeSubagentTasks, agentId),),],internal: true,@@ -2300,7 +2365,6 @@ export async function createRun({}const streamLimits = resolveStreamLimits(agentsEndpointConfig);- const resolvedRunId = runId ?? randomUUID();/*** Built as a variable (not an inline literal) so the extra@@ -2320,7 +2384,11 @@ export async function createRun({fadingTiers,indexTokenCountMap,subagentUsageSink,- subagentTasks,+ subagentTasks: activeSubagentTasks,+ ...(runFilesActive &&+ runFiles != null && {+ subagentContext: { prepare: runFiles.prepare, complete: runFiles.complete },+ }),// Exclude side-effecting / large-free-form-arg tools from eager execution.// Eager speculatively runs a tool mid-stream; for a big streamed arg (a// file body, a bash heredoc, a code block) the accumulated args can divergediff --git a/packages/api/src/agents/tools.ts b/packages/api/src/agents/tools.tsindex 5b23429b5a..b2a651ae2b 100644--- a/packages/api/src/agents/tools.ts+++ b/packages/api/src/agents/tools.ts@@ -1,4 +1,5 @@import {+ Tools,Constants,normalizeActionToolName,normalizeServerName,@@ -61,6 +62,30 @@ export function isCodeSessionToolName();}+/** Tools that consume shared code, search, or image resources need current file records. */+export function isFileResourceToolName(name: string): boolean {+ return (+ isCodeFileToolName(name) ||+ isCodeSessionToolName(name) ||+ name === Tools.file_search ||+ name === 'image_gen_oai' ||+ name === 'image_edit_oai' ||+ name === 'gemini_image_gen'+ );+}++/** File-authoring artifacts opt in explicitly; other tool artifacts keep their normal delivery. */+export function isCodeArtifactToolOutput(output: { name: string; artifact?: unknown }): boolean {+ const artifact = output.artifact;+ return (+ isCodeSessionToolName(output.name) ||+ (artifact != null &&+ typeof artifact === 'object' &&+ HOST_FILE_AUTHORING_ARTIFACT_KEY in artifact &&+ artifact[HOST_FILE_AUTHORING_ARTIFACT_KEY] === true)+ );+}+interface ToolDefLike {name: string;[key: string]: unknown;diff --git a/packages/api/src/agents/validation.spec.ts b/packages/api/src/agents/validation.spec.tsindex f0b83ccc1c..3b00381d64 100644--- a/packages/api/src/agents/validation.spec.ts+++ b/packages/api/src/agents/validation.spec.ts@@ -261,6 +261,17 @@ describe('agentCreateSchema with subagents', () => {expect(result.success).toBe(true);});+ it.each([true, false])('preserves the explicit file sharing choice %s', (shareFiles) => {+ const result = agentCreateSchema.parse({+ ...base,+ subagents: { enabled: true, shareFiles },+ });+ expect(result.subagents?.shareFiles).toBe(shareFiles);+ expect(agentUpdateSchema.parse({ subagents: { shareFiles } }).subagents?.shareFiles).toBe(+ shareFiles,+ );+ });+it('accepts the current-agent placeholder in a graph subagent', () => {const result = agentCreateSchema.safeParse({...base,diff --git a/packages/api/src/agents/validation.ts b/packages/api/src/agents/validation.tsindex 47e917267d..fb52df7bc8 100644--- a/packages/api/src/agents/validation.ts+++ b/packages/api/src/agents/validation.ts@@ -362,6 +362,7 @@ export const agentSubagentsSchema: z.ZodOptional<z.ZodType<AgentSubagentsConfig>.object({enabled: z.boolean().optional(),allowSelf: z.boolean().optional(),+ shareFiles: z.boolean().optional(),agent_ids: z.array(z.string()).optional(),graphs: z.array(graphSubagentSchema).optional(),})diff --git a/packages/api/src/endpoints/config/endpoints.spec.ts b/packages/api/src/endpoints/config/endpoints.spec.tsindex 34c2aa42cb..bee644dfd0 100644--- a/packages/api/src/endpoints/config/endpoints.spec.ts+++ b/packages/api/src/endpoints/config/endpoints.spec.ts@@ -177,6 +177,32 @@ describe('createEndpointsConfigService', () => {expect(result?.[EModelEndpoint.agents]?.maxSubagents).toBe(20);});+ it.each([true, false])(+ 'exposes file sharing policy to the agent builder when enabled=%s',+ async (enabled) => {+ const fileSharing = {+ enabled,+ allowSiblingSharing: false,+ maxFiles: 100,+ ttlMs: 3_600_000,+ };+ const deps = createMockDeps({+ loadDefaultEndpointsConfig: jest.fn().mockResolvedValue({+ [EModelEndpoint.agents]: { userProvide: false, order: 0 },+ }),+ getAppConfig: jest+ .fn()+ .mockResolvedValue(+ appConfig({ endpoints: { [EModelEndpoint.agents]: { fileSharing } } }),+ ),+ });+ const { getEndpointsConfig } = createEndpointsConfigService(deps);+ const result = await getEndpointsConfig(fakeReq());++ expect(result?.[EModelEndpoint.agents]?.fileSharing).toEqual(fileSharing);+ },+ );+it('exposes the deployment stateful environment allowlist', async () => {const deps = createMockDeps({loadDefaultEndpointsConfig: jest.fn().mockResolvedValue({diff --git a/packages/api/src/endpoints/config/endpoints.ts b/packages/api/src/endpoints/config/endpoints.tsindex 746f00955b..4e2cf87a3e 100644--- a/packages/api/src/endpoints/config/endpoints.ts+++ b/packages/api/src/endpoints/config/endpoints.ts@@ -71,8 +71,14 @@ export function createEndpointsConfigService(deps: EndpointsConfigDeps): {}if (mergedConfig[EModelEndpoint.agents] && appConfig?.endpoints?.[EModelEndpoint.agents]) {- const { disableBuilder, capabilities, allowedProviders, statefulCodeSessions, maxSubagents } =- appConfig.endpoints[EModelEndpoint.agents];+ const {+ disableBuilder,+ capabilities,+ allowedProviders,+ statefulCodeSessions,+ maxSubagents,+ fileSharing,+ } = appConfig.endpoints[EModelEndpoint.agents];const toolApproval = appConfig.endpoints[EModelEndpoint.agents].toolApproval;/** Only advertise Accept edits when the endpoint fallback cannot force every* unmatched tool back to Ask/Deny. Explicit rules and hooks remain free to@@ -114,6 +120,7 @@ export function createEndpointsConfigService(deps: EndpointsConfigDeps): {capabilities,statefulCodeSessions: clientStatefulCodeSessions,maxSubagents,+ fileSharing,};}diff --git a/packages/api/src/files/code/index.ts b/packages/api/src/files/code/index.tsindex c587875727..78b3eabb11 100644--- a/packages/api/src/files/code/index.ts+++ b/packages/api/src/files/code/index.ts@@ -6,5 +6,9 @@ export * from './extract';export * from './form';export * from './identity';export * from './image';+export * from './inspection';export * from './preflight';export * from './priming';+export * from './process';+export * from './publication';+export * from './snapshot';diff --git a/packages/api/src/files/code/inspection.ts b/packages/api/src/files/code/inspection.tsnew file mode 100644index 0000000000..9a9c1b6ef1--- /dev/null+++ b/packages/api/src/files/code/inspection.ts@@ -0,0 +1,63 @@+import path from 'node:path';+import { inferMimeType } from 'librechat-data-provider';+import type { PreparedCodeOutput } from './preflight';+import { extractCodeArtifactRawText, extractCodeArtifactInspectionText } from './extract';+import { sanitizeArtifactPath } from '~/utils/files';+import { classifyCodeArtifact } from './classify';++export type CodeOutputTypeDetector = (+ buffer: Buffer,+ returnFileType: true,+) => Promise<{ mime: string } | undefined | null>;++/** Inspects supplied bytes without downloading them or adding them to a request cache. */+export async function prepareCodeOutputBufferForInspection({+ buffer,+ name,+ fileSizeLimit,+ inspectContent = true,+ determineFileType,+ classify = classifyCodeArtifact,+ extractRawText = extractCodeArtifactRawText,+ extractInspectionText = extractCodeArtifactInspectionText,+}: {+ buffer: Buffer;+ name: string;+ fileSizeLimit: number;+ inspectContent?: boolean;+ determineFileType: CodeOutputTypeDetector;+ classify?: typeof classifyCodeArtifact;+ extractRawText?: typeof extractCodeArtifactRawText;+ extractInspectionText?: typeof extractCodeArtifactInspectionText;+}): Promise<PreparedCodeOutput> {+ const safeName = sanitizeArtifactPath(name);+ const fallbackType = inferMimeType(name, '') || 'application/octet-stream';+ const file = { name, filename: safeName, type: fallbackType };+ if (!inspectContent) return { buffer, file };+ if (buffer.length > fileSizeLimit) {+ return { buffer, extractedTextComplete: false, file };+ }++ const detectedType = await determineFileType(buffer, true);+ const detectedMimeType = detectedType?.mime?.toLowerCase();+ if (detectedMimeType?.startsWith('image/')) {+ return { buffer, extractedTextComplete: false, file: { ...file, type: detectedMimeType } };+ }++ const leafName = path.basename(safeName);+ const unknownText = detectedType == null ? extractRawText(buffer, 'utf8-text') : null;+ const mimeType = unknownText != null ? 'text/plain' : (detectedMimeType ?? fallbackType);+ const category = unknownText != null ? 'utf8-text' : classify(leafName, mimeType);+ const content = unknownText ?? extractRawText(buffer, category);+ const extractedText = await extractInspectionText(buffer, leafName, mimeType, category);+ return {+ buffer,+ extractedTextComplete: extractedText.complete,+ file: {+ ...file,+ type: mimeType,+ content: content ?? undefined,+ extractedText: extractedText.text ?? undefined,+ },+ };+}diff --git a/packages/api/src/files/code/process.ts b/packages/api/src/files/code/process.tsnew file mode 100644index 0000000000..9aa4d1d970--- /dev/null+++ b/packages/api/src/files/code/process.ts@@ -0,0 +1,622 @@+import path from 'path';+import { v4 } from 'uuid';+import {+ megabyte,+ fileConfig,+ imageExtRegex,+ inferMimeType,+ mergeCodeEnvRef,+} from 'librechat-data-provider';+import type { CodeEnvRef, FileSources, getEndpointFileConfig } from 'librechat-data-provider';+import type { CodeFileCommitData } from '@librechat/data-schemas';+import type {+ CodeOutputResult,+ CodeOutputStoredFile,+ CodeOutputPersistence,+ CodeOutputPublication,+ CodeOutputDownloadFallback,+ ProcessPublishedCodeOutputInput,+} from './publication';+import type { sanitizeArtifactPath, flattenArtifactPath } from '~/utils/files';+import type { classifyCodeArtifact, CodeArtifactCategory } from './classify';+import type { hasOfficeHtmlPath, getExtractedTextFormat } from './extract';+import type { RetentionExpiry } from '~/files/retention';+import type { extractCodeArtifactText } from './extract';+import type { logAxiosError } from '~/utils/axios';+import type { ServerRequest } from '~/types';+import { createCodeOutputPersistence } from './publication';++export type CodeOutputProcessorInput = Omit<+ ProcessPublishedCodeOutputInput,+ 'publication' | 'agentId'+> & {+ req: ServerRequest & Required<Pick<ServerRequest, 'user' | 'config'>>;+ agentId?: string;+ toolCallId?: string;+ freshClaimAfter?: number;+ downloadFallback?: boolean;+ publication?: CodeOutputPublication;+};++type DownloadInput = Pick<+ CodeOutputProcessorInput,+ 'req' | 'id' | 'session_id' | 'codeApiBaseUrl' | 'executionProfile' | 'bridgeWorkerId'+> & { maxBytes: number };++type DownloadFallbackInput = Pick<+ CodeOutputProcessorInput,+ | 'id'+ | 'name'+ | 'agentId'+ | 'messageId'+ | 'toolCallId'+ | 'session_id'+ | 'conversationId'+ | 'executionProfile'+ | 'executionRouteKey'+> & { expiresAt: number };++export interface CodeOutputProcessorDeps {+ getCodeOutputFileSettings: (req: ServerRequest) => {+ endpointFileConfig: ReturnType<typeof getEndpointFileConfig>;+ fileSizeLimit: number;+ };+ downloadCodeOutputBuffer: (input: DownloadInput) => Promise<Buffer>;+ createDownloadFallback: (input: DownloadFallbackInput) => CodeOutputDownloadFallback;+ getRetentionExpiry: (req: ServerRequest) => Promise<RetentionExpiry>;+ convertImage: (+ req: ServerRequest,+ buffer: Buffer,+ detail: 'high',+ filename: string,+ ) => Promise<+ Pick<+ CodeOutputStoredFile,+ 'filepath' | 'bytes' | 'width' | 'height' | 'storageKey' | 'storageRegion'+ >+ >;+ getStrategyFunctions: (source: FileSources) => {+ saveBuffer?: (input: {+ userId: string;+ buffer: Buffer;+ fileName: string;+ basePath: string;+ tenantId?: string;+ }) => Promise<string>;+ };+ determineFileType: (+ buffer: Buffer,+ reportErrors: boolean,+ ) => Promise<{ mime: string } | undefined>;+ claimCodeFile: CodeOutputPersistence['claim'];+ commitCodeFile: (data: CodeFileCommitData, sourceDispatchedAt?: number) => Promise<boolean>;+ finalizePreview: (input: {+ buffer: Buffer;+ leafName: string;+ mimeType: string;+ category: CodeArtifactCategory;+ file_id: string;+ previewRevision?: string | null;+ }) => Promise<CodeOutputStoredFile | null>;+ hasOfficeHtmlPath: typeof hasOfficeHtmlPath;+ sanitizeArtifactPath: typeof sanitizeArtifactPath;+ flattenArtifactPath: typeof flattenArtifactPath;+ classifyCodeArtifact: typeof classifyCodeArtifact;+ extractCodeArtifactText: typeof extractCodeArtifactText;+ getExtractedTextFormat: typeof getExtractedTextFormat;+ getStorageMetadata: (+ file: Pick<CodeOutputStoredFile, 'filepath' | 'source' | 'storageKey' | 'storageRegion'>,+ ) => Pick<CodeOutputStoredFile, 'storageKey' | 'storageRegion'>;+ logAxiosError: typeof logAxiosError;+ logger: { warn: (message: string) => void; debug: (message: string) => void };+}++/** Persists ordinary outputs or explicit publications, returning owned preview work separately. */+export async function processCodeOutput(+ {+ req,+ id,+ name,+ toolCallId,+ conversationId,+ messageId,+ session_id,+ agentId,+ freshClaimAfter,+ codeApiBaseUrl,+ executionProfile = 'default',+ executionRouteKey = executionProfile,+ bridgeWorkerId,+ preparedBuffer,+ downloadFallback,+ publication,+ }: CodeOutputProcessorInput,+ {+ getCodeOutputFileSettings,+ downloadCodeOutputBuffer,+ createDownloadFallback,+ getRetentionExpiry,+ convertImage,+ getStrategyFunctions,+ determineFileType,+ claimCodeFile,+ commitCodeFile: commitOutput,+ finalizePreview,+ hasOfficeHtmlPath,+ sanitizeArtifactPath,+ flattenArtifactPath,+ classifyCodeArtifact,+ extractCodeArtifactText,+ getExtractedTextFormat,+ getStorageMetadata,+ logAxiosError,+ logger,+ }: CodeOutputProcessorDeps,+): Promise<CodeOutputResult | null> {+ const appConfig = req.config;+ const currentDate = new Date();+ const fileExt = path.extname(name).toLowerCase();+ const isImage = fileExt && imageExtRegex.test(name);++ const { endpointFileConfig, fileSizeLimit } = getCodeOutputFileSettings(req);++ try {+ const formattedDate = currentDate.toISOString();+ if (downloadFallback === true) {+ return {+ file: createDownloadFallback({+ id,+ name,+ agentId,+ messageId,+ toolCallId,+ session_id,+ conversationId,+ executionProfile,+ executionRouteKey,+ expiresAt: currentDate.getTime() + 86400000,+ }),+ };+ }+ const retentionExpiryPromise = getRetentionExpiry(req);+ const buffer =+ preparedBuffer ??+ (await downloadCodeOutputBuffer({+ req,+ id,+ session_id,+ maxBytes: fileSizeLimit,+ codeApiBaseUrl,+ executionProfile,+ bridgeWorkerId,+ }));++ // Enforce file size limit+ if (buffer.length > fileSizeLimit) {+ logger.warn(+ `[processCodeOutput] File "${name}" (${(buffer.length / megabyte).toFixed(2)} MB) exceeds size limit of ${(fileSizeLimit / megabyte).toFixed(2)} MB, falling back to download URL`,+ );+ return {+ file: createDownloadFallback({+ id,+ name,+ agentId,+ messageId,+ toolCallId,+ session_id,+ conversationId,+ executionProfile,+ executionRouteKey,+ expiresAt: currentDate.getTime() + 86400000,+ }),+ };+ }++ /* Code-output files belong to the user who ran the execution.+ * SessionKey on codeapi will be `<tenant>:user:<userId>` for these,+ * so cache and access stay user-private. */+ const codeEnvRef: CodeEnvRef = {+ kind: 'user',+ id: req.user.id,+ storage_session_id: session_id,+ file_id: id,+ executionProfile,+ ...(executionRouteKey !== executionProfile ? { executionRouteKey } : {}),+ };++ /* `safeName` keeps the directory structure (`a/b/file.txt` -> `a/b/file.txt`)+ * so the next prime() can place the file at the same nested path in the+ * sandbox; flattening would re-create the bug where every nested artifact+ * collapsed into the root and read_file calls 404'd. The flat-form+ * storage key is composed below once `file_id` is known so we can cap+ * the total length at filesystem NAME_MAX. */+ const safeName = sanitizeArtifactPath(name);+ if (safeName !== name) {+ logger.warn(+ `[processCodeOutput] Filename sanitized: "${name}" -> "${safeName}" | conv=${conversationId}`,+ );+ }++ /**+ * Ordinary outputs atomically reuse a file_id for this filename and conversation.+ * Explicit publications instead receive a fresh attempt ID from the gateway.+ *+ * Claim by `safeName` (not raw `name`) so the claim and the eventual+ * `createFile` agree on the filename column — otherwise weird inputs+ * (e.g. `"proj name/[email protected]"`) would claim under the raw name and+ * then write under the sanitized one, leaving the claim row orphaned.+ */+ /**+ * Dispatch-order stamp persisted with every write AND every claim insert+ * (foreground writes dispatch ≈ now): the out-of-order guard below+ * compares WRITER dispatch order, not wall-clock write time — an older+ * task writing late must not make a newer task's harvest look stale, and+ * a freshly claimed row must carry its claimant's stamp before the+ * content write lands.+ */+ const sourceDispatchedAt = freshClaimAfter ?? Date.now();++ const outputPersistence = createCodeOutputPersistence({+ publication,+ claim: claimCodeFile,+ commit: commitCodeFile,+ });+ const newFileId = v4();+ const claimed = await outputPersistence.claim({+ filename: safeName,+ conversationId,+ file_id: newFileId,+ user: req.user.id,+ tenantId: req.user.tenantId,+ sourceDispatchedAt,+ });+ const file_id = claimed.file_id;+ const isUpdate = file_id !== newFileId;++ /**+ * Out-of-order guard for detached (background) harvests: when the claimed+ * row's last writer was dispatched AFTER this task (`freshClaimAfter` =+ * this task's dispatch time), a newer run owns this filename slot. The+ * `(filename, conversationId)` unique index means the stale bytes have+ * nowhere else to live, so skip this file rather than overwrite fresh+ * content — the harvest's stdout patch still lands, only the superseded+ * attachment is omitted. Falls back to `updatedAt` for rows written+ * before the stamp existed (the claim itself is timestamp-neutral).+ */+ const lastWriterDispatchedAt =+ claimed.metadata?.sourceDispatchedAt ??+ (claimed.updatedAt != null ? new Date(claimed.updatedAt).getTime() : null);+ if (isUpdate && freshClaimAfter != null && (lastWriterDispatchedAt ?? 0) > freshClaimAfter) {+ logger.warn(+ `[processCodeOutput] Skipping stale background output "${safeName}" (${file_id}): a newer run owns this filename`,+ );+ return null;+ }++ if (isUpdate) {+ logger.debug(+ `[processCodeOutput] Updating existing file "${safeName}" (${file_id}) instead of creating duplicate`,+ );+ }++ /**+ * The data-schema method checks background dispatch ownership atomically with+ * the write. A superseded commit misses and its attachment is skipped.+ * Bytes already uploaded to a reused storage key retain the existing race;+ * a per-file lock would be needed to cover that storage write as well.+ * Foreground outputs retain their unconditional commit behavior.+ */+ async function commitCodeFile(fileData: CodeOutputStoredFile): Promise<boolean> {+ const committed = await commitOutput(+ fileData,+ freshClaimAfter == null ? undefined : sourceDispatchedAt,+ );+ if (!committed) {+ logger.warn(+ `[processCodeOutput] Skipping stale background output "${safeName}" (${file_id}): a newer run owns this filename`,+ );+ }+ return committed;+ }++ /**+ * Preserve the original `messageId` on update. Each `processCodeOutput`+ * call would otherwise overwrite it with the current run's run id, which+ * decouples the file from the assistant message that originally created+ * it. `getCodeGeneratedFiles` filters by `messageId IN <thread>`, so a+ * stale id (e.g. from a later regeneration / failed re-read attempt)+ * silently excludes the file from priming on subsequent turns.+ */+ const persistedMessageId = isUpdate ? (claimed.messageId ?? messageId) : messageId;+ /* A generated-output write replaces the file's bytes, so pointers to+ * earlier content in another profile must not survive as reusable refs. */+ const codeEnvReferenceSet = mergeCodeEnvRef(undefined, codeEnvRef);+ const codeEnvMetadata = {+ ...claimed.metadata,+ ...codeEnvReferenceSet,+ sourceDispatchedAt,+ };++ if (isImage) {+ const usage = isUpdate ? (claimed.usage ?? 0) + 1 : 1;+ const _file = await convertImage(req, buffer, 'high', `${file_id}${fileExt}`);+ const filepath = usage > 1 ? `${_file.filepath}?v=${Date.now()}` : _file.filepath;+ const storageMetadata = getStorageMetadata({+ filepath: _file.filepath,+ source: appConfig.fileStrategy,+ storageKey: _file.storageKey,+ storageRegion: _file.storageRegion,+ });+ outputPersistence.trackStored({+ ..._file,+ ...storageMetadata,+ file_id,+ filepath: _file.filepath,+ filename: safeName,+ type: `image/${appConfig.imageOutputType}`,+ user: req.user.id,+ tenantId: req.user.tenantId,+ conversationId,+ source: appConfig.fileStrategy,+ });+ const file: CodeOutputStoredFile & Pick<CodeEnvRef, 'executionProfile'> = {+ ..._file,+ filepath,+ ...storageMetadata,+ file_id,+ messageId: persistedMessageId,+ usage,+ filename: safeName,+ conversationId,+ executionProfile,+ user: req.user.id,+ tenantId: req.user.tenantId,+ type: `image/${appConfig.imageOutputType}`,+ createdAt: isUpdate ? claimed.createdAt : formattedDate,+ updatedAt: formattedDate,+ source: appConfig.fileStrategy,+ context: outputPersistence.context,+ metadata: codeEnvMetadata,+ ...(await retentionExpiryPromise),+ };+ if (!(await outputPersistence.commit(file))) {+ return null;+ }+ return { file: Object.assign(file, { messageId, toolCallId, agentId }) };+ }++ const { saveBuffer } = getStrategyFunctions(appConfig.fileStrategy);+ if (!saveBuffer) {+ logger.warn(+ `[processCodeOutput] saveBuffer not available for strategy ${appConfig.fileStrategy}, falling back to download URL`,+ );+ return {+ file: createDownloadFallback({+ id,+ name,+ agentId,+ messageId,+ toolCallId,+ session_id,+ conversationId,+ executionProfile,+ executionRouteKey,+ expiresAt: currentDate.getTime() + 86400000,+ }),+ };+ }++ const detectedType = await determineFileType(buffer, true);+ const mimeType = detectedType?.mime || inferMimeType(name, '') || 'application/octet-stream';++ /** Check MIME type support - for code-generated files, we're lenient but log unsupported types */+ const isSupportedMimeType = fileConfig.checkType(+ mimeType,+ endpointFileConfig.supportedMimeTypes,+ );+ if (!isSupportedMimeType) {+ logger.warn(+ `[processCodeOutput] File "${name}" has unsupported MIME type "${mimeType}", proceeding with storage but may not be usable as tool resource`,+ );+ }++ /* Compose the storage key here, after `file_id` is known, so the+ * `flattenArtifactPath` cap budget can be calculated against the+ * actual prefix length. The full key has to fit in one filesystem+ * path component (NAME_MAX = 255 on most filesystems); without this+ * cap, deeply-nested artifact paths whose individual segments were+ * within bounds can still produce a flat form that overflows once+ * `${file_id}__` is prepended, causing `ENAMETOOLONG` inside+ * saveBuffer and falling back to a download URL. The 255 figure is+ * the conservative cross-platform NAME_MAX (Linux ext4, NTFS, APFS).+ */+ const NAME_MAX = 255;+ const flatName = flattenArtifactPath(safeName, NAME_MAX - file_id.length - 2);+ const fileName = `${file_id}__${flatName}`;+ const filepath = await saveBuffer({+ userId: req.user.id,+ buffer,+ fileName,+ basePath: 'uploads',+ tenantId: req.user.tenantId,+ });+ const storageMetadata = getStorageMetadata({+ filepath,+ source: appConfig.fileStrategy,+ });+ outputPersistence.trackStored({+ file_id,+ filepath,+ ...storageMetadata,+ filename: safeName,+ type: mimeType,+ bytes: buffer.length,+ user: req.user.id,+ tenantId: req.user.tenantId,+ conversationId,+ source: appConfig.fileStrategy,+ });++ /* `classifyCodeArtifact` and `extractCodeArtifactText` make+ * extension/bare-name decisions on the input string. With the+ * path-preserving sanitizer they can now receive a nested path like+ * `reports.v1/Makefile`, which the classifier's `extensionOf` reads+ * as `v1/Makefile` (the slice after the dot in the directory name)+ * and the bare-name branch rejects because it sees a `.` anywhere in+ * the string. Result: extensionless artifacts under dotted folders+ * (Makefile, Dockerfile, etc.) get misclassified as `other` and+ * skip text extraction. Pass the basename so classification matches+ * what it would have gotten with the old flat-name flow. */+ const leafName = path.basename(safeName);+ const category = classifyCodeArtifact(leafName, mimeType);++ /* Office-bucket files (DOCX/XLSX/XLS/ODS/CSV/PPTX) route through+ * `bufferToOfficeHtml` which is CPU-heavy. Persist the record now+ * with `status: 'pending'` and `text: null` so the agent's response+ * isn't blocked, then return a `finalize` thunk the caller can run+ * in the background. Non-office files have cheap or no extraction+ * — run it inline so the caller gets a fully-resolved record+ * without juggling a finalize step. */+ const expectsPreview = hasOfficeHtmlPath(leafName, mimeType);++ const baseFile: CodeOutputStoredFile = {+ file_id,+ filepath,+ ...storageMetadata,+ messageId: persistedMessageId,+ object: 'file',+ filename: safeName,+ type: mimeType,+ conversationId,+ user: req.user.id,+ tenantId: req.user.tenantId,+ bytes: buffer.length,+ updatedAt: formattedDate,+ metadata: codeEnvMetadata,+ source: appConfig.fileStrategy,+ context: outputPersistence.context,+ usage: isUpdate ? (claimed.usage ?? 0) + 1 : 1,+ createdAt: isUpdate ? claimed.createdAt : formattedDate,+ ...(await retentionExpiryPromise),+ };++ if (expectsPreview) {+ /* Persist with `status: 'pending'` and explicit+ * `text: null` / `textFormat: null` so an update that previously+ * had cached text gets cleared. The deferred finalize transitions+ * to 'ready' (with text/textFormat) or 'failed' (with+ * previewError).+ *+ * `previewRevision` is a fresh UUID stamped on every emit. The+ * deferred finalize's `updateFile` is conditional on this — if+ * a newer turn (cross-turn filename reuse) has rotated the+ * revision before this render finishes, the stale render is+ * silently discarded rather than overwriting the newer record.+ * (Codex P1 review on PR #12957.) */+ const previewRevision = v4();+ const file = {+ ...baseFile,+ text: null,+ textFormat: null,+ status: 'pending',+ previewError: null,+ previewRevision,+ } satisfies CodeOutputStoredFile;+ if (!(await outputPersistence.commit(file))) {+ return null;+ }+ return {+ file: Object.assign(file, { messageId, toolCallId, agentId }),+ finalize: outputPersistence.finalize(file, () =>+ finalizePreview({+ buffer,+ leafName,+ mimeType,+ category,+ file_id: file.file_id,+ previewRevision: file.previewRevision,+ }),+ ),+ previewRevision: file.previewRevision,+ };+ }++ /* Non-office path: extraction is cheap (utf8 decode, parseDocument+ * for PDF/ODT, or null for binaries). Run inline and return a+ * fully-resolved record — no `finalize` needed. */+ const text = await extractCodeArtifactText(buffer, leafName, mimeType, category);+ /* `textFormat` accompanies `text` so the client can gate+ * office-HTML-bucket routing on a trusted signal — clients MUST+ * NOT inject `text` into the iframe as HTML unless `textFormat ===+ * 'html'`. RAG-uploaded `.docx` etc. arrive with plain text from+ * mammoth.extractRawText and would otherwise be hijacked by the+ * extension-based office routing into the HTML-injection path+ * (Codex P1 review on PR #12934). null on extract failure — the+ * client treats absence as 'text' for safety. */+ const textFormat = getExtractedTextFormat(leafName, mimeType, text);+ const file: CodeOutputStoredFile = {+ ...baseFile,+ // Always set explicitly so an update which produces a binary or+ // oversized artifact clears any previously cached text — createFile+ // uses findOneAndUpdate with $set semantics.+ text: text ?? null,+ textFormat: textFormat ?? null,+ // Clear deferred-preview lifecycle fields in case the prior emit+ // at this (filename, conversationId) was an office file —+ // otherwise stale `pending`/`failed` would persist and the client+ // would render the wrong state for the now non-office artifact.+ status: null,+ previewError: null,+ previewRevision: null,+ };++ if (!(await outputPersistence.commit(file))) {+ return null;+ }+ return { file: Object.assign(file, { messageId, toolCallId, agentId }) };+ } catch (error) {+ if (+ error != null &&+ typeof error === 'object' &&+ 'code' in error &&+ error.code === 'CODE_OUTPUT_DOWNLOAD_LIMIT'+ ) {+ logger.warn(+ `[processCodeOutput] Generated file exceeds size limit of ${(fileSizeLimit / megabyte).toFixed(2)} MB, falling back to download URL`,+ );+ }+ if (+ error != null &&+ typeof error === 'object' &&+ 'message' in error &&+ error.message === 'Path traversal detected in filename'+ ) {+ logger.warn(+ `[processCodeOutput] Path traversal blocked for file "${name}" | conv=${conversationId}`,+ );+ }+ logAxiosError({+ message: 'Error downloading/processing code environment file',+ error,+ });+ logger.warn(+ `[processCodeOutput] Falling back to Code API download URL for strategy ${appConfig.fileStrategy}`,+ );++ // Fallback for download errors - return download URL so user can still manually download+ return {+ file: createDownloadFallback({+ id,+ name,+ agentId,+ messageId,+ toolCallId,+ session_id,+ conversationId,+ executionProfile,+ executionRouteKey,+ expiresAt: currentDate.getTime() + 86400000,+ }),+ };+ }+}diff --git a/packages/api/src/files/code/publication.spec.ts b/packages/api/src/files/code/publication.spec.tsnew file mode 100644index 0000000000..449061c3a2--- /dev/null+++ b/packages/api/src/files/code/publication.spec.ts@@ -0,0 +1,487 @@+import { FileContext, FileSources } from 'librechat-data-provider';+import type { RunArtifactFile, RunArtifactScope } from '@librechat/data-schemas';+import type { RunFileProvenance } from 'librechat-data-provider';+import type {+ ProcessPublishedCodeOutputInput,+ CodeOutputDownloadFallback,+ CodeOutputPublication,+ CodeOutputStoredFile,+} from './publication';+import { createCodeOutputPersistence, createRunArtifactPublisher } from './publication';++const scope: RunArtifactScope = {+ userId: 'user-a',+ tenantId: 'tenant-a',+ conversationId: 'conversation-a',+ runId: 'run-a',+ executionId: 'child-a',+ agentId: 'agent-a',+ sourceFileId: 'sandbox-a',+};++const provenance: RunFileProvenance = {+ runId: scope.runId,+ executionId: scope.executionId,+ agentId: scope.agentId,+ sourceFileId: scope.sourceFileId,+ parentExecutionId: 'parent-a',+ publishedAt: '2026-09-11T16:00:00.000Z',+ inputFileIds: ['input-pdf'],+};++function storedFile(file_id = 'attempt-a'): CodeOutputStoredFile {+ return {+ file_id,+ user: scope.userId,+ tenantId: scope.tenantId ?? undefined,+ conversationId: scope.conversationId,+ filename: 'report.csv',+ filepath: `/uploads/${file_id}/report.csv`,+ type: 'text/csv',+ source: FileSources.local,+ bytes: 12,+ previewRevision: `preview-${file_id}`,+ metadata: {+ codeEnvRef: {+ kind: 'user',+ id: scope.userId,+ storage_session_id: 'child-sandbox',+ file_id: scope.sourceFileId,+ },+ },+ };+}++function downloadFallback(): CodeOutputDownloadFallback {+ return {+ filename: 'report.csv',+ filepath: '/api/files/code/download/child-sandbox/sandbox-a',+ expiresAt: 1_789_232_400_000,+ conversationId: scope.conversationId,+ toolCallId: 'tool-call-a',+ messageId: scope.runId,+ agentId: scope.agentId,+ };+}++function publishedFile(file = storedFile()): RunArtifactFile {+ return {+ ...file,+ file_id: 'canonical-artifact',+ conversationId: scope.conversationId,+ object: 'file',+ context: FileContext.run_artifact,+ embedded: false,+ usage: 1,+ text: file.text ?? undefined,+ status: file.status ?? undefined,+ previewError: file.previewError ?? undefined,+ previewRevision: file.previewRevision ?? undefined,+ metadata: { ...file.metadata, runFile: provenance },+ };+}++function publication(overrides: Partial<CodeOutputPublication> = {}): CodeOutputPublication {+ return {+ scope,+ provenance,+ publish: jest.fn(async () => publishedFile()),+ find: jest.fn(async () => null),+ discard: jest.fn(async () => undefined),+ ...overrides,+ };+}++describe('Code output publication gateway', () => {+ it('preserves the ordinary code-output claim, commit, and preview behavior', async () => {+ const claim = jest.fn(async (input: { file_id: string }) => ({ file_id: input.file_id }));+ const commit = jest.fn(async () => true);+ const persistence = createCodeOutputPersistence({ claim, commit });+ const input = {+ filename: 'report.csv',+ conversationId: scope.conversationId,+ file_id: 'ordinary-id',+ user: scope.userId,+ };+ expect(await persistence.claim(input)).toEqual({ file_id: 'ordinary-id' });+ expect(claim).toHaveBeenCalledWith(input);+ const file = storedFile();+ expect(await persistence.commit(file)).toBe(true);+ expect(commit).toHaveBeenCalledWith(file);+ const finalize = async () => file;+ expect(persistence.finalize(file, finalize)).toBe(finalize);+ expect(persistence.context).toBe(FileContext.execute_code);+ });++ it('uses a unique attempt ID until publication and then returns the canonical file identity', async () => {+ const boundary = publication();+ const legacyClaim = jest.fn();+ const legacyCommit = jest.fn();+ const persistence = createCodeOutputPersistence({+ publication: boundary,+ claim: legacyClaim,+ commit: legacyCommit,+ });+ expect(+ await persistence.claim({+ filename: 'report.csv',+ conversationId: scope.conversationId,+ file_id: 'attempt-a',+ user: scope.userId,+ tenantId: scope.tenantId,+ }),+ ).toEqual({ file_id: 'attempt-a' });+ const file = storedFile();+ expect(await persistence.commit(file)).toBe(true);+ expect(file.file_id).toBe('canonical-artifact');+ expect(file.previewRevision).toBe('preview-attempt-a');+ expect(legacyClaim).not.toHaveBeenCalled();+ expect(legacyCommit).not.toHaveBeenCalled();+ expect(boundary.discard).not.toHaveBeenCalled();+ const finalize = async () => file;+ expect(persistence.finalize(file, finalize)).toBe(finalize);+ });++ it('cleans the losing attempt without deleting source sandbox files or finalizing the winner', async () => {+ const boundary = publication();+ const persistence = createCodeOutputPersistence({+ publication: boundary,+ claim: jest.fn(),+ commit: jest.fn(),+ });+ const loser = storedFile('attempt-b');+ await persistence.commit(loser);+ expect(boundary.discard).toHaveBeenCalledWith(+ expect.objectContaining({+ file_id: 'attempt-b',+ filepath: '/uploads/attempt-b/report.csv',+ embedded: false,+ metadata: undefined,+ }),+ );+ expect(loser.file_id).toBe('canonical-artifact');+ expect(loser.filepath).toBe('/uploads/attempt-a/report.csv');+ expect(persistence.finalize(loser, async () => loser)).toBeUndefined();+ });++ it('recovers an acknowledged-late publication without deleting its stored bytes', async () => {+ const boundary = publication({+ publish: jest.fn(async () => {+ throw new Error('write acknowledgement lost');+ }),+ find: jest.fn(async () => publishedFile()),+ });+ const persistence = createCodeOutputPersistence({+ publication: boundary,+ claim: jest.fn(),+ commit: jest.fn(),+ });+ const file = storedFile();+ await persistence.commit(file);+ expect(file.file_id).toBe('canonical-artifact');+ expect(boundary.discard).not.toHaveBeenCalled();+ });++ it('removes an unpublished attempt after a confirmed storage metadata failure', async () => {+ const boundary = publication({+ publish: jest.fn(async () => {+ throw new Error('database unavailable');+ }),+ });+ const persistence = createCodeOutputPersistence({+ publication: boundary,+ claim: jest.fn(),+ commit: jest.fn(),+ });+ await expect(persistence.commit(storedFile())).rejects.toThrow('database unavailable');+ expect(boundary.discard).toHaveBeenCalledTimes(1);+ });++ it('keeps stored bytes when an uncertain write cannot be reconciled', async () => {+ const boundary = publication({+ publish: jest.fn(async () => {+ throw new Error('write acknowledgement lost');+ }),+ find: jest.fn(async () => {+ throw new Error('read unavailable');+ }),+ });+ const persistence = createCodeOutputPersistence({+ publication: boundary,+ claim: jest.fn(),+ commit: jest.fn(),+ });+ await expect(persistence.commit(storedFile())).rejects.toThrow('read unavailable');+ expect(boundary.discard).not.toHaveBeenCalled();+ });++ it('cleans an attempt cancelled after byte storage and before metadata commit', async () => {+ const controller = new AbortController();+ const boundary = publication({ signal: controller.signal });+ const persistence = createCodeOutputPersistence({+ publication: boundary,+ claim: jest.fn(),+ commit: jest.fn(),+ });+ controller.abort(new Error('Artifact generation expired'));+ await expect(persistence.commit(storedFile())).rejects.toThrow('generation expired');+ expect(boundary.publish).not.toHaveBeenCalled();+ expect(boundary.find).not.toHaveBeenCalled();+ expect(boundary.discard).toHaveBeenCalledWith(+ expect.objectContaining({+ file_id: 'attempt-a',+ metadata: undefined,+ }),+ );+ });++ it('rejects a different user, tenant, or conversation before publication', async () => {+ const boundary = publication();+ const persistence = createCodeOutputPersistence({+ publication: boundary,+ claim: jest.fn(),+ commit: jest.fn(),+ });+ for (const difference of [+ { user: 'other-user' },+ { tenantId: 'other-tenant' },+ { conversationId: 'other-conversation' },+ ]) {+ await expect(persistence.commit({ ...storedFile(), ...difference })).rejects.toThrow(+ 'publication owner',+ );+ }+ expect(boundary.publish).not.toHaveBeenCalled();+ });+});++describe('Run artifact publisher', () => {+ const artifact = { id: scope.sourceFileId, name: 'report.csv', sessionId: 'child-sandbox' };++ function dependencies() {+ return {+ claimRunArtifactFile: jest.fn(async () => ({ file_id: 'canonical-artifact' })),+ publishRunArtifactFile: jest.fn(async () => publishedFile()),+ findRunArtifactFile: jest.fn(async () => publishedFile()),+ processCodeOutput: jest.fn(async (input: ProcessPublishedCodeOutputInput) => ({+ file: await input.publication.publish({ scope, provenance, file: publishedFile() }),+ })),+ prepare: jest.fn(async () => Buffer.from('a,b\n1,2')),+ discard: jest.fn(async () => undefined),+ finalize: jest.fn(),+ };+ }++ it('replays a durable publication without downloading or processing its source again', async () => {+ const deps = dependencies();+ const publish = createRunArtifactPublisher({+ ...deps,+ claimRunArtifactFile: async () => ({ file_id: 'canonical-artifact', file: publishedFile() }),+ });+ expect(await publish({ scope, provenance, artifact })).toEqual(publishedFile());+ expect(deps.prepare).not.toHaveBeenCalled();+ expect(deps.processCodeOutput).not.toHaveBeenCalled();+ });++ it('reuses inspected bytes and starts preview finalization after durable verification', async () => {+ const deps = dependencies();+ const publish = createRunArtifactPublisher(deps);+ expect(await publish({ scope, provenance, artifact })).toEqual(publishedFile());+ expect(deps.processCodeOutput).toHaveBeenCalledWith(+ expect.objectContaining({+ id: artifact.id,+ name: artifact.name,+ session_id: artifact.sessionId,+ preparedBuffer: Buffer.from('a,b\n1,2'),+ publication: expect.objectContaining({ scope, provenance }),+ }),+ );+ expect(deps.finalize).toHaveBeenCalledTimes(1);+ expect(deps.findRunArtifactFile).not.toHaveBeenCalled();+ });++ it('fails publication when existing output processing returns a transient download fallback', async () => {+ const deps = dependencies();+ const publish = createRunArtifactPublisher({+ ...deps,+ processCodeOutput: async () => ({+ file: downloadFallback(),+ }),+ });+ await expect(publish({ scope, provenance, artifact })).rejects.toThrow('durable storage');+ expect(deps.finalize).not.toHaveBeenCalled();+ });++ it('rejects durable-looking metadata that did not pass through publication', async () => {+ const deps = dependencies();+ const publish = createRunArtifactPublisher({+ ...deps,+ processCodeOutput: async () => ({ file: publishedFile() }),+ });+ await expect(publish({ scope, provenance, artifact })).rejects.toThrow('could not be verified');+ expect(deps.finalize).not.toHaveBeenCalled();+ });++ it('does not read or download a generation that has already been cancelled', async () => {+ const deps = dependencies();+ const controller = new AbortController();+ controller.abort(new Error('Generation superseded'));+ await expect(+ createRunArtifactPublisher(deps)({ scope, provenance, artifact, signal: controller.signal }),+ ).rejects.toThrow('superseded');+ expect(deps.claimRunArtifactFile).not.toHaveBeenCalled();+ expect(deps.prepare).not.toHaveBeenCalled();+ });++ it('does not store bytes when a generation expires during inspection', async () => {+ const deps = dependencies();+ const controller = new AbortController();+ deps.prepare.mockImplementationOnce(async () => {+ controller.abort(new Error('Generation superseded'));+ return Buffer.from('newer generation bytes');+ });+ await expect(+ createRunArtifactPublisher(deps)({ scope, provenance, artifact, signal: controller.signal }),+ ).rejects.toThrow('superseded');+ expect(deps.processCodeOutput).not.toHaveBeenCalled();+ expect(deps.publishRunArtifactFile).not.toHaveBeenCalled();+ });++ it('finishes a committed preview without returning a cancelled attachment', async () => {+ const deps = dependencies();+ const controller = new AbortController();+ deps.publishRunArtifactFile.mockImplementationOnce(async () => {+ controller.abort(new Error('Caller cancelled after commit'));+ return publishedFile();+ });+ await expect(+ createRunArtifactPublisher(deps)({ scope, provenance, artifact, signal: controller.signal }),+ ).rejects.toThrow('cancelled after commit');+ expect(deps.finalize).toHaveBeenCalledTimes(1);+ expect(deps.discard).not.toHaveBeenCalled();+ });++ it.each(['throw', 'fallback'] as const)(+ 'removes stored bytes when processing fails before commit (%s)',+ async (failure) => {+ const deps = dependencies();+ const publish = createRunArtifactPublisher({+ ...deps,+ processCodeOutput: async (input) => {+ const persistence = createCodeOutputPersistence({+ publication: input.publication,+ claim: jest.fn(),+ commit: jest.fn(),+ });+ persistence.trackStored(storedFile('uncommitted'));+ if (failure === 'throw') throw new Error('Processing failed before metadata');+ return { file: downloadFallback() };+ },+ });+ await expect(publish({ scope, provenance, artifact })).rejects.toThrow();+ expect(deps.discard).toHaveBeenCalledTimes(1);+ expect(deps.discard).toHaveBeenCalledWith(+ expect.objectContaining({+ file_id: 'uncommitted',+ filepath: '/uploads/uncommitted/report.csv',+ metadata: undefined,+ }),+ );+ expect(deps.publishRunArtifactFile).not.toHaveBeenCalled();+ },+ );++ it('does not delete a committed winner if processing later fails', async () => {+ const deps = dependencies();+ const publish = createRunArtifactPublisher({+ ...deps,+ processCodeOutput: async (input) => {+ const persistence = createCodeOutputPersistence({+ publication: input.publication,+ claim: jest.fn(),+ commit: jest.fn(),+ });+ const file = storedFile();+ persistence.trackStored(file);+ await persistence.commit(file);+ throw new Error('Processor failed after commit');+ },+ });+ await expect(publish({ scope, provenance, artifact })).rejects.toThrow('after commit');+ expect(deps.discard).not.toHaveBeenCalled();+ });++ it('cleans a tracked duplicate once without deleting its winner', async () => {+ const deps = dependencies();+ const publish = createRunArtifactPublisher({+ ...deps,+ processCodeOutput: async (input) => {+ const persistence = createCodeOutputPersistence({+ publication: input.publication,+ claim: jest.fn(),+ commit: jest.fn(),+ });+ const file = storedFile('loser');+ persistence.trackStored(file);+ await persistence.commit(file);+ return { file };+ },+ });+ expect(await publish({ scope, provenance, artifact })).toEqual(publishedFile());+ expect(deps.discard).toHaveBeenCalledTimes(1);+ expect(deps.discard).toHaveBeenCalledWith(expect.objectContaining({ file_id: 'loser' }));+ });++ it('retains tracked bytes when neither a lost write acknowledgement nor its recovery can be resolved', async () => {+ const deps = dependencies();+ deps.publishRunArtifactFile.mockRejectedValue(new Error('Write acknowledgement lost'));+ deps.findRunArtifactFile.mockRejectedValue(new Error('Recovery read unavailable'));+ const publish = createRunArtifactPublisher({+ ...deps,+ processCodeOutput: async (input) => {+ const persistence = createCodeOutputPersistence({+ publication: input.publication,+ claim: jest.fn(),+ commit: jest.fn(),+ });+ const file = storedFile();+ persistence.trackStored(file);+ await persistence.commit(file);+ return { file };+ },+ });+ await expect(publish({ scope, provenance, artifact })).rejects.toThrow(+ 'Recovery read unavailable',+ );+ expect(deps.discard).not.toHaveBeenCalled();+ });++ it('preserves cancellation after cleaning a processor download fallback', async () => {+ const deps = dependencies();+ const controller = new AbortController();+ const publish = createRunArtifactPublisher({+ ...deps,+ processCodeOutput: async (input) => {+ const persistence = createCodeOutputPersistence({+ publication: input.publication,+ claim: jest.fn(),+ commit: jest.fn(),+ });+ const file = storedFile();+ persistence.trackStored(file);+ controller.abort(new Error('Generation expired'));+ try {+ await persistence.commit(file);+ } catch {+ /* Matches the legacy fallback. */+ }+ return { file: downloadFallback() };+ },+ });+ await expect(+ publish({ scope, provenance, artifact, signal: controller.signal }),+ ).rejects.toThrow('Generation expired');+ expect(deps.discard).toHaveBeenCalledTimes(1);+ expect(deps.publishRunArtifactFile).not.toHaveBeenCalled();+ });+});diff --git a/packages/api/src/files/code/publication.ts b/packages/api/src/files/code/publication.tsnew file mode 100644index 0000000000..8121a2c346--- /dev/null+++ b/packages/api/src/files/code/publication.ts@@ -0,0 +1,327 @@+import { FileContext, FileSources } from 'librechat-data-provider';+import type {+ RunArtifactFile,+ RunArtifactClaim,+ RunArtifactScope,+ RunArtifactContent,+ CodeFileCommitData,+ PublishRunArtifactInput,+} from '@librechat/data-schemas';+import type { RunFileProvenance, TFile } from 'librechat-data-provider';+import type { CodeExecutionContext } from '~/agents/execution';++export type CodeOutputStoredFile = CodeFileCommitData;++export type CodeOutputDownloadFallback = Pick<TFile, 'filename' | 'filepath' | 'conversationId'> & {+ expiresAt: number;+ messageId?: string;+ toolCallId?: string;+ agentId?: string;+};++interface CodeOutputClaimInput {+ filename: string;+ conversationId: string;+ file_id: string;+ user: string;+ tenantId?: string | null;+ sourceDispatchedAt?: number;+}++interface CodeOutputClaim {+ file_id: string;+ usage?: number;+ messageId?: string;+ createdAt?: Date | string;+ updatedAt?: Date | string;+ metadata?: TFile['metadata'];+}++export interface CodeOutputPublication {+ scope: RunArtifactScope;+ provenance: RunFileProvenance;+ publish: (input: PublishRunArtifactInput) => Promise<RunArtifactFile>;+ find: (scope: RunArtifactScope) => Promise<RunArtifactFile | null>;+ discard: (file: TFile) => Promise<void>;+ /** Includes the shared run lifetime as well as request cancellation. */+ signal?: AbortSignal;+ /** Attempt-local ownership notifications; no database row exists for this object yet. */+ trackStored?: (file: TFile) => void;+ releaseStored?: (file: TFile) => void;+}++export interface CodeOutputPersistence {+ context: FileContext;+ claim: (input: CodeOutputClaimInput) => Promise<CodeOutputClaim>;+ commit: (file: CodeOutputStoredFile) => Promise<boolean>;+ trackStored: (file: CodeOutputStoredFile) => void;+ finalize: <T>(+ file: CodeOutputStoredFile,+ finalize: () => Promise<T>,+ ) => (() => Promise<T>) | undefined;+}++function artifactContent(file: CodeOutputStoredFile): RunArtifactContent {+ return {+ ...file,+ text: file.text ?? undefined,+ status: file.status ?? undefined,+ previewError: file.previewError ?? undefined,+ previewRevision: file.previewRevision ?? undefined,+ };+}++function storedObject(file: CodeOutputStoredFile): TFile {+ return {+ ...artifactContent(file),+ file_id: file.file_id,+ user: file.user,+ tenantId: file.tenantId,+ object: 'file',+ embedded: false,+ usage: 0,+ metadata: undefined,+ };+}++function sameStoredObject(left: CodeOutputStoredFile, right: RunArtifactFile): boolean {+ return (+ left.source === right.source &&+ (left.storageKey ?? left.filepath) === (right.storageKey ?? right.filepath)+ );+}++/** Reuses code-output storage while giving every publication attempt a separate object key. */+export function createCodeOutputPersistence({+ publication,+ claim,+ commit,+}: {+ publication?: CodeOutputPublication;+ claim: (input: CodeOutputClaimInput) => Promise<CodeOutputClaim>;+ commit: (file: CodeOutputStoredFile) => Promise<boolean>;+}): CodeOutputPersistence {+ if (publication == null) {+ return {+ context: FileContext.execute_code,+ claim,+ commit,+ trackStored: () => undefined,+ finalize: (_file, finalize) => finalize,+ };+ }+ const ownedFiles = new WeakSet<CodeOutputStoredFile>();+ const discardAttempt = async (file: CodeOutputStoredFile): Promise<void> => {+ const stored = storedObject(file);+ await publication.discard(stored);+ publication.releaseStored?.(stored);+ };+ return {+ context: FileContext.run_artifact,+ trackStored: (file) => publication.trackStored?.(storedObject(file)),+ claim: async (input) => {+ publication.signal?.throwIfAborted();+ if (+ input.user !== publication.scope.userId ||+ (input.tenantId ?? null) !== (publication.scope.tenantId ?? null) ||+ input.conversationId !== publication.scope.conversationId+ ) {+ throw new Error('The generated file does not match its publication owner');+ }+ return { file_id: input.file_id };+ },+ commit: async (file) => {+ if (+ file.user !== publication.scope.userId ||+ (file.tenantId ?? null) !== (publication.scope.tenantId ?? null) ||+ file.conversationId !== publication.scope.conversationId+ ) {+ throw new Error('The generated file does not match its publication owner');+ }+ // Storage writes finish before the processor hands us the complete record.+ // Cancellation at that boundary must remove the uncommitted attempt object.+ if (publication.signal?.aborted) {+ await discardAttempt(file);+ publication.signal.throwIfAborted();+ }+ let published: RunArtifactFile;+ try {+ published = await publication.publish({+ scope: publication.scope,+ provenance: publication.provenance,+ file: artifactContent(file),+ });+ } catch (error) {+ let recovered: RunArtifactFile | null;+ try {+ recovered = await publication.find(publication.scope);+ } catch (readError) {+ // The write may have committed. Deleting its bytes while the database+ // cannot answer would corrupt a durable publication.+ publication.releaseStored?.(storedObject(file));+ throw readError;+ }+ if (recovered == null) {+ await discardAttempt(file);+ throw error;+ }+ published = recovered;+ }+ if (sameStoredObject(file, published)) {+ ownedFiles.add(file);+ publication.releaseStored?.(storedObject(file));+ } else {+ await discardAttempt(file);+ }+ Object.assign(file, published);+ return true;+ },+ finalize: (file, finalize) => (ownedFiles.has(file) ? finalize : undefined),+ };+}++export interface RunArtifactDescriptor {+ id: string;+ name: string;+ sessionId: string;+ /** Opaque host-owned copy; never an agent-supplied filesystem path. */+ snapshotId?: string;+ codeExecutionContext?: Pick<+ CodeExecutionContext,+ 'baseUrl' | 'executionProfile' | 'executionRouteKey' | 'bridgeWorkerId'+ >;+}++export interface ProcessPublishedCodeOutputInput {+ id: string;+ name: string;+ session_id: string;+ conversationId: string;+ messageId: string;+ agentId: string;+ publication: CodeOutputPublication;+ preparedBuffer?: Buffer;+ codeApiBaseUrl?: string;+ executionProfile?: CodeExecutionContext['executionProfile'];+ executionRouteKey?: string;+ bridgeWorkerId?: string;+}++export interface CodeOutputResult {+ file: CodeOutputStoredFile | CodeOutputDownloadFallback | null;+ finalize?: () => Promise<CodeOutputStoredFile | null>;+ previewRevision?: string;+}++export interface PublishedCodeOutputResult extends CodeOutputResult {+ file: CodeOutputStoredFile;+}++export interface PublishGeneratedRunArtifactInput {+ scope: RunArtifactScope;+ provenance: RunFileProvenance;+ artifact: RunArtifactDescriptor;+ signal?: AbortSignal;+}++export function createRunArtifactPublisher({+ claimRunArtifactFile,+ publishRunArtifactFile,+ findRunArtifactFile,+ processCodeOutput,+ prepare,+ discard,+ finalize,+}: {+ claimRunArtifactFile: (scope: RunArtifactScope) => Promise<RunArtifactClaim>;+ publishRunArtifactFile: CodeOutputPublication['publish'];+ findRunArtifactFile: CodeOutputPublication['find'];+ processCodeOutput: (input: ProcessPublishedCodeOutputInput) => Promise<CodeOutputResult | null>;+ prepare: (artifact: RunArtifactDescriptor, signal?: AbortSignal) => Promise<Buffer>;+ discard: CodeOutputPublication['discard'];+ finalize: (result: PublishedCodeOutputResult) => void;+}): (input: PublishGeneratedRunArtifactInput) => Promise<RunArtifactFile> {+ return async ({ scope, provenance, artifact, signal }) => {+ signal?.throwIfAborted();+ if (+ provenance.sourceFileId !== scope.sourceFileId ||+ provenance.runId !== scope.runId ||+ provenance.executionId !== scope.executionId ||+ provenance.agentId !== scope.agentId ||+ artifact.sessionId.trim().length === 0+ ) {+ throw new Error('The generated artifact does not match its publication identity');+ }+ const existing = await claimRunArtifactFile(scope);+ signal?.throwIfAborted();+ if (existing.file != null) {+ return existing.file;+ }+ const preparedBuffer = await prepare(artifact, signal);+ signal?.throwIfAborted();+ const publicationResult: { file: RunArtifactFile | null } = { file: null };+ const pendingObjects = new Map<string, TFile>();+ const objectKey = (file: TFile): string =>+ JSON.stringify([file.source, file.storageKey ?? file.filepath]);+ try {+ const result = await processCodeOutput({+ id: artifact.id,+ name: artifact.name,+ session_id: artifact.sessionId,+ conversationId: scope.conversationId,+ messageId: scope.runId,+ agentId: scope.agentId,+ preparedBuffer,+ codeApiBaseUrl: artifact.codeExecutionContext?.baseUrl,+ executionProfile: artifact.codeExecutionContext?.executionProfile,+ executionRouteKey: artifact.codeExecutionContext?.executionRouteKey,+ bridgeWorkerId: artifact.codeExecutionContext?.bridgeWorkerId,+ publication: {+ scope,+ provenance,+ signal,+ trackStored: (file) => pendingObjects.set(objectKey(file), file),+ releaseStored: (file) => pendingObjects.delete(objectKey(file)),+ publish: async (input) => {+ signal?.throwIfAborted();+ const file = await publishRunArtifactFile(input);+ publicationResult.file = file;+ pendingObjects.delete(objectKey(file));+ return file;+ },+ find: async (identity) => {+ const file = await findRunArtifactFile(identity);+ publicationResult.file = file;+ if (file != null) pendingObjects.delete(objectKey(file));+ return file;+ },+ discard,+ },+ });+ const file = result?.file;+ if (+ file == null ||+ !('file_id' in file) ||+ file.context !== FileContext.run_artifact ||+ file.source === FileSources.execute_code+ ) {+ signal?.throwIfAborted();+ throw new Error('The generated artifact could not be published to durable storage');+ }+ const published = publicationResult.file;+ if (published == null || published.file_id !== file.file_id) {+ throw new Error('The generated artifact publication could not be verified');+ }+ // Complete previews for a record that committed before cancellation; emitting+ // the attachment still waits for the cancellation check below.+ finalize({ ...result, file });+ signal?.throwIfAborted();+ return published;+ } finally {+ // The legacy processor can fail after saving bytes but before it constructs+ // its complete metadata. Its storage notifications make those failures owned+ // by this attempt, while committed or uncertain objects were released above.+ await Promise.all([...pendingObjects.values()].map((file) => discard(file)));+ }+ };+}diff --git a/packages/api/src/files/code/snapshot.spec.ts b/packages/api/src/files/code/snapshot.spec.tsnew file mode 100644index 0000000000..9a8fafc8fb--- /dev/null+++ b/packages/api/src/files/code/snapshot.spec.ts@@ -0,0 +1,222 @@+import axios from 'axios';+import { PassThrough, Readable } from 'node:stream';+import { FileSources } from 'librechat-data-provider';+import { buffer as consumeBuffer } from 'node:stream/consumers';+import type { AxiosResponse, InternalAxiosRequestConfig } from 'axios';+import type { FiltersConfig } from 'librechat-data-provider';+import type { RunArtifactDescriptor } from './publication';+import type { ServerRequest } from '~/types';+import { createRunFileSnapshotStore } from '~/agents/files/snapshots';+import { createRunArtifactSnapshotAdapter } from './snapshot';++const source: RunArtifactDescriptor = {+ id: 'file ?#',+ name: 'reports/result.csv',+ sessionId: 'session ?#',+ codeExecutionContext: {+ baseUrl: 'https://selected-worker.test/code/',+ executionProfile: 'stateful',+ executionRouteKey: 'worker-route',+ bridgeWorkerId: 'worker-id',+ },+};++function setup({+ open = () => Readable.from([Buffer.from('name,total\na,10\n')]),+ headers = {},+ filters,+ maxBytes = 1024,+ fileLimit = 10,+}: {+ open?: () => Readable;+ headers?: Record<string, string>;+ filters?: FiltersConfig;+ maxBytes?: number;+ fileLimit?: number;+} = {}) {+ const transport = jest.fn(+ async (config: InternalAxiosRequestConfig): Promise<AxiosResponse<Readable>> => ({+ config,+ data: open(),+ status: 200,+ statusText: 'OK',+ headers,+ }),+ );+ const request = axios.create({ adapter: transport });+ const req = { body: {} } as ServerRequest;+ req.user = { id: 'user+id' } as ServerRequest['user'];+ req.config = {+ config: {},+ fileStrategy: FileSources.local,+ imageOutputType: 'png',+ filters,+ fileConfig: {+ endpoints: {+ agents: { fileSizeLimit: maxBytes / (1024 * 1024), fileLimit },+ },+ },+ };+ const getAuthHeaders = jest.fn(async () => ({ Authorization: 'Bearer test-token' }));+ const getBaseURL = jest.fn(() => 'https://default-worker.test');+ const determineFileType = jest.fn(async (): Promise<{ mime: string } | undefined> => undefined);+ const adapter = createRunArtifactSnapshotAdapter({+ req,+ request,+ getAuthHeaders,+ getBaseURL,+ determineFileType,+ });+ return { adapter, transport, req, getAuthHeaders, getBaseURL, determineFileType };+}++describe('createRunArtifactSnapshotAdapter', () => {+ it('downloads the trusted worker route with scoped auth and encoded resource identity', async () => {+ const { adapter, transport, req, getAuthHeaders, getBaseURL } = setup();+ const controller = new AbortController();++ await expect(consumeBuffer(await adapter.open(source, controller.signal))).resolves.toEqual(+ Buffer.from('name,total\na,10\n'),+ );++ expect(getAuthHeaders).toHaveBeenCalledWith(req, 'worker-id');+ expect(getBaseURL).not.toHaveBeenCalled();+ expect(transport).toHaveBeenCalledWith(+ expect.objectContaining({+ url: 'https://selected-worker.test/code/download/session%20%3F%23/file%20%3F%23?kind=user&id=user%2Bid',+ responseType: 'stream',+ timeout: 15000,+ signal: controller.signal,+ headers: expect.objectContaining({+ Authorization: 'Bearer test-token',+ 'X-CodeAPI-Expected-Profile': 'stateful',+ 'X-LibreChat-Code-Worker-ID': 'worker-id',+ }),+ }),+ );+ });++ it('publishes inspected immutable bytes without downloading the changed sandbox file again', async () => {+ let current = Buffer.from('name,total\na,10\n');+ const { adapter, transport, determineFileType } = setup({+ open: () => Readable.from([current]),+ });+ const snapshots = createRunFileSnapshotStore({+ open: adapter.open,+ maxBytes: 1024,+ maxFiles: 2,+ });+ try {+ const snapshot = await snapshots.capture(source);+ current = Buffer.from('name,total\na,999\n');+ const captured = await snapshots.read(snapshot.snapshotId);++ await expect(adapter.prepare(source, captured)).resolves.toBe(captured);+ expect(captured.toString()).toBe('name,total\na,10\n');+ expect(transport).toHaveBeenCalledTimes(1);+ expect(determineFileType).not.toHaveBeenCalled();+ } finally {+ await snapshots.close();+ }+ });++ it('applies content filters to the captured bytes rather than trusting metadata or redownloading', async () => {+ const { adapter, transport, determineFileType } = setup({+ filters: {+ files: {+ pii: {+ fields: ['content'],+ starterPatterns: [],+ customPatterns: [{ id: 'private', label: 'private token', regex: 'PRIVATE-[A-Z]+' }],+ },+ },+ },+ });++ await expect(adapter.prepare(source, Buffer.from('PRIVATE-SECRET'))).rejects.toMatchObject({+ body: { source: 'file', field: 'content' },+ });+ expect(determineFileType).toHaveBeenCalledWith(Buffer.from('PRIVATE-SECRET'), true);+ expect(transport).not.toHaveBeenCalled();+ });++ it('rejects a binary snapshot when policy requires complete extracted text', async () => {+ const { adapter, determineFileType } = setup({+ filters: {+ files: { pii: { fields: ['extracted_text'], starterPatterns: [], uninspectable: 'block' } },+ },+ });+ determineFileType.mockResolvedValue({ mime: 'image/png' });++ await expect(adapter.prepare(source, Buffer.from([0, 1, 2, 3]))).rejects.toMatchObject({+ code: 'content_filter_uninspectable',+ body: { source: 'file', field: 'extracted_text' },+ });+ });++ it('does not fall back to a mutable download when inspection exceeds configured limits', async () => {+ const { adapter, transport } = setup({ maxBytes: 4 });+ await expect(adapter.prepare(source, Buffer.from('large'))).rejects.toThrow(+ 'could not pass file inspection',+ );+ const disabled = setup({ fileLimit: 0 });+ await expect(disabled.adapter.prepare(source, Buffer.from('ok'))).rejects.toThrow(+ 'could not pass file inspection',+ );+ expect(transport).not.toHaveBeenCalled();+ expect(disabled.transport).not.toHaveBeenCalled();+ });++ it('rejects oversized advertised and chunked bodies and closes their streams', async () => {+ const advertised = new PassThrough();+ const withLength = setup({+ maxBytes: 4,+ headers: { 'content-length': '5' },+ open: () => advertised,+ });+ await expect(withLength.adapter.open(source)).rejects.toThrow('response too large');+ expect(advertised.destroyed).toBe(true);++ const chunked = Readable.from([Buffer.from('123'), Buffer.from('45')]);+ const withoutLength = setup({ maxBytes: 4, open: () => chunked });+ await expect(consumeBuffer(await withoutLength.adapter.open(source))).rejects.toThrow(+ 'response too large',+ );+ expect(chunked.destroyed).toBe(true);+ });++ it('propagates source failures and closes an unfinished download when cancelled', async () => {+ const broken = new PassThrough();+ const failed = setup({ open: () => broken });+ const reading = consumeBuffer(await failed.adapter.open(source));+ broken.destroy(new Error('connection reset'));+ await expect(reading).rejects.toThrow('connection reset');++ const pending = new PassThrough();+ const cancelled = setup({ open: () => pending });+ const controller = new AbortController();+ const stream = await cancelled.adapter.open(source, controller.signal);+ const cancelledRead = consumeBuffer(stream);+ controller.abort();+ await expect(cancelledRead).rejects.toMatchObject({ name: 'AbortError' });+ expect(pending.destroyed).toBe(true);+ });++ it('checks cancellation before auth, download, and publication', async () => {+ const { adapter, transport, getAuthHeaders, determineFileType } = setup();+ const controller = new AbortController();+ controller.abort();++ await expect(adapter.open(source, controller.signal)).rejects.toMatchObject({+ name: 'AbortError',+ });+ await expect(+ adapter.prepare(source, Buffer.from('safe'), controller.signal),+ ).rejects.toMatchObject({+ name: 'AbortError',+ });+ expect(getAuthHeaders).not.toHaveBeenCalled();+ expect(transport).not.toHaveBeenCalled();+ expect(determineFileType).not.toHaveBeenCalled();+ });+});diff --git a/packages/api/src/files/code/snapshot.ts b/packages/api/src/files/code/snapshot.tsnew file mode 100644index 0000000000..05134b1ba3--- /dev/null+++ b/packages/api/src/files/code/snapshot.ts@@ -0,0 +1,137 @@+import { pipeline } from 'node:stream/promises';+import { EModelEndpoint, getEndpointFileConfig, mergeFileConfig } from 'librechat-data-provider';+import type { Readable } from 'node:stream';+import type { AxiosInstance } from 'axios';+import type { RunArtifactDescriptor } from './publication';+import type { CodeOutputTypeDetector } from './inspection';+import type { ServerRequest } from '~/types';+import {+ assertRemoteFileContentLength,+ createRemoteFileByteLimitTransform,+ DEFAULT_REMOTE_FILE_FETCH_TIMEOUT_MS,+} from '~/storage/url';+import {+ getBoundedCodeOutputByteLimit,+ preflightCodeOutputBatch,+ CODE_OUTPUT_PREFLIGHT_MAX_COUNT,+} from './preflight';+import { codeServerHttpAgent, codeServerHttpsAgent } from '~/utils/code';+import { prepareCodeOutputBufferForInspection } from './inspection';+import { codeExecutionHeaders } from '~/agents/execution';+import { buildCodeEnvDownloadQuery } from './identity';++export interface RunArtifactSnapshotAdapter {+ open: (artifact: RunArtifactDescriptor, signal?: AbortSignal) => Promise<Readable>;+ prepare: (+ artifact: RunArtifactDescriptor,+ buffer: Buffer,+ signal?: AbortSignal,+ ) => Promise<Buffer>;+}++/** Downloads privately once; publication inspects that immutable copy with the normal file policy. */+export function createRunArtifactSnapshotAdapter({+ req,+ request,+ getAuthHeaders,+ getBaseURL,+ determineFileType,+}: {+ req: ServerRequest;+ request: AxiosInstance;+ getAuthHeaders: (req: ServerRequest, bridgeWorkerId?: string) => Promise<Record<string, string>>;+ getBaseURL: (profile: 'default' | 'stateful') => string;+ determineFileType: CodeOutputTypeDetector;+}): RunArtifactSnapshotAdapter {+ const fileConfig = mergeFileConfig(req.config?.fileConfig);+ const endpointLimits = getEndpointFileConfig({ fileConfig, endpoint: EModelEndpoint.agents });+ const limits = {+ fileLimit: endpointLimits.fileLimit ?? CODE_OUTPUT_PREFLIGHT_MAX_COUNT,+ fileSizeLimit: getBoundedCodeOutputByteLimit(+ endpointLimits.fileSizeLimit ?? fileConfig.serverFileSizeLimit,+ ),+ totalSizeLimit: getBoundedCodeOutputByteLimit(endpointLimits.totalSizeLimit),+ };+ const fileSizeLimit = Math.min(limits.fileSizeLimit, limits.totalSizeLimit);++ async function open(artifact: RunArtifactDescriptor, signal?: AbortSignal): Promise<Readable> {+ signal?.throwIfAborted();+ const userId = req.user?.id;+ if (!userId) throw new Error('A user identity is required to snapshot generated files.');+ if ([artifact.id, artifact.sessionId].some((id) => !id || id === '.' || id === '..')) {+ throw new Error('The generated artifact has no valid sandbox identity.');+ }+ const {+ executionProfile = 'default',+ bridgeWorkerId,+ baseUrl,+ } = artifact.codeExecutionContext ?? {};+ const baseURL = (baseUrl ?? getBaseURL(executionProfile)).replace(/\/+$/, '');+ const authHeaders = await getAuthHeaders(req, bridgeWorkerId);+ signal?.throwIfAborted();+ const query = buildCodeEnvDownloadQuery({ kind: 'user', id: userId });+ const response = await request<Readable>({+ method: 'get',+ url: `${baseURL}/download/${encodeURIComponent(artifact.sessionId)}/${encodeURIComponent(artifact.id)}${query}`,+ responseType: 'stream',+ headers: {+ 'User-Agent': 'LibreChat/1.0',+ ...authHeaders,+ ...codeExecutionHeaders({ executionProfile, bridgeWorkerId }),+ },+ httpAgent: codeServerHttpAgent,+ httpsAgent: codeServerHttpsAgent,+ timeout: DEFAULT_REMOTE_FILE_FETCH_TIMEOUT_MS,+ maxContentLength: fileSizeLimit,+ maxBodyLength: fileSizeLimit,+ signal,+ });+ try {+ signal?.throwIfAborted();+ assertRemoteFileContentLength(+ { 'content-length': String(response.headers['content-length'] ?? '') },+ fileSizeLimit,+ );+ const bounded = createRemoteFileByteLimitTransform(fileSizeLimit);+ // Pipeline forwards source errors and consumer cancellation in both directions.+ // Its rejection is also delivered by the returned stream to the snapshot store.+ void pipeline(response.data, bounded, { signal }).catch(() => undefined);+ return bounded;+ } catch (error) {+ response.data.destroy();+ throw error;+ }+ }++ async function prepare(+ artifact: RunArtifactDescriptor,+ buffer: Buffer,+ signal?: AbortSignal,+ ): Promise<Buffer> {+ signal?.throwIfAborted();+ const entries = await preflightCodeOutputBatch({+ filters: req.config?.filters,+ artifact: {+ session_id: artifact.sessionId,+ files: [{ id: artifact.id, name: artifact.name }],+ },+ limits,+ prepare: ({ maxBytes, inspectContent }) =>+ prepareCodeOutputBufferForInspection({+ buffer,+ name: artifact.name,+ fileSizeLimit: Math.min(fileSizeLimit, maxBytes),+ inspectContent,+ determineFileType,+ }),+ });+ signal?.throwIfAborted();+ const preparedBuffer = entries[0]?.preparedBuffer;+ if (!preparedBuffer || entries[0]?.downloadFallback) {+ throw new Error('The private artifact snapshot could not pass file inspection.');+ }+ return preparedBuffer;+ }++ return { open, prepare };+}diff --git a/packages/api/src/files/context.ts b/packages/api/src/files/context.tsindex 735bb63ab1..211f5a0783 100644--- a/packages/api/src/files/context.ts+++ b/packages/api/src/files/context.ts@@ -1,6 +1,5 @@import { logger } from '@librechat/data-schemas';import { FileSources, mergeFileConfig } from 'librechat-data-provider';-import type { IMongoFile } from '@librechat/data-schemas';import type { TFile } from 'librechat-data-provider';import type { TokenCountFn } from '~/utils/text';import type { ServerRequest } from '~/types';@@ -44,7 +43,10 @@ export async function extractFileContext({req,tokenCountFn,}: {- attachments: IMongoFile[];+ attachments: readonly (Pick<TFile, 'text' | 'filename'> & {+ source?: string;+ llmDeliveryPath?: string;+ })[];req?: ServerRequest;tokenCountFn: TokenCountFn;}): Promise<string | undefined> {diff --git a/packages/api/src/files/documents/libreoffice.spec.ts b/packages/api/src/files/documents/libreoffice.spec.tsindex 449ade21bc..5ca96ccbe1 100644--- a/packages/api/src/files/documents/libreoffice.spec.ts+++ b/packages/api/src/files/documents/libreoffice.spec.ts@@ -1,6 +1,6 @@-import { spawnSync } from 'child_process';import * as fs from 'fs';import * as path from 'path';+import { spawnSync } from 'child_process';import {_resetLibreOfficeProbeCache,buildPdfEmbedDocument,@@ -231,11 +231,10 @@ describe('libreoffice (env gating + wrapper)', () => {});it('never throws — falls through to null on any conversion failure', async () => {- /* Even if the binary IS available, a malformed buffer should- * cause `convertOfficeToPdf` to throw and `tryLibreOfficePreview`- * to swallow it. The dispatcher pipeline takes over from there. */+ /* Truncate a real OOXML archive: LibreOffice can successfully+ * autodetect plain text despite a .docx extension. */process.env.OFFICE_PREVIEW_LIBREOFFICE = 'true';- const garbage = Buffer.from('this-is-definitely-not-a-docx');+ const garbage = readFixture('sample.docx').subarray(0, 64);let threw = false;try {const out = await tryLibreOfficePreview(garbage, 'docx', 512 * 1024);diff --git a/packages/api/src/files/documents/sample.pptx b/packages/api/src/files/documents/sample.pptxnew file mode 100644index 0000000000..63a3cb051aBinary files /dev/null and b/packages/api/src/files/documents/sample.pptx differdiff --git a/packages/api/src/files/filter.ts b/packages/api/src/files/filter.tsindex 02dc91a3ec..f6881ac134 100644--- a/packages/api/src/files/filter.ts+++ b/packages/api/src/files/filter.ts@@ -5,7 +5,7 @@ import {fileConfig,} from 'librechat-data-provider';import type { AppConfig, IMongoFile } from '@librechat/data-schemas';-import type { RegexLike } from 'librechat-data-provider';+import type { RegexLike, TFile } from 'librechat-data-provider';import type { ServerRequest } from '~/types';/**@@ -65,10 +65,15 @@ export function isLegacyFileUploadUX(return endpointFileConfig?.legacyFileUploadUX === true;}-export function filterFilesByEndpointRuntimeConfig(+type EndpointPolicyFile = Pick<TFile, 'bytes' | 'type'> & {+ source?: string;+ metadata?: { routingMimeType?: string };+};++export function filterFilesByEndpointRuntimeConfig<T extends EndpointPolicyFile>(appConfig: AppConfig | undefined,params: {- files: IMongoFile[] | undefined;+ files: T[] | undefined;endpoint?: string | null;endpointType?: string | null;/** Bytes already committed by an earlier call, so a request split across several@@ -77,7 +82,7 @@ export function filterFilesByEndpointRuntimeConfig(skipTotalSizeLimit?: boolean;preserveTextSources?: boolean;},-): IMongoFile[] {+): T[] {const {files,endpoint,@@ -133,7 +138,7 @@ export function filterFilesByEndpointRuntimeConfig(/** Filter by total size limit - keep files until total exceeds limit */if (!skipTotalSizeLimit && totalSizeLimit !== undefined && totalSizeLimit > 0) {let totalSize = consumedBytes;- const withinTotalLimit: IMongoFile[] = [];+ const withinTotalLimit: T[] = [];for (let i = 0; i < filteredFiles.length; i++) {const file = filteredFiles[i];diff --git a/packages/api/src/middleware/__tests__/concurrency.cache_integration.spec.ts b/packages/api/src/middleware/__tests__/concurrency.cache_integration.spec.tsindex 4c29fdad55..13a976a276 100644--- a/packages/api/src/middleware/__tests__/concurrency.cache_integration.spec.ts+++ b/packages/api/src/middleware/__tests__/concurrency.cache_integration.spec.ts@@ -1,4 +1,5 @@import type { Redis, Cluster } from 'ioredis';+import { closeRedisClients } from '../../cache/__tests__/redisClients.helper';/*** Integration tests for concurrency middleware atomic Lua scripts.@@ -61,17 +62,7 @@ describe('Concurrency Middleware Integration Tests', () => {});afterAll(async () => {- if (ioredisClient) {- try {- await ioredisClient.quit();- } catch {- try {- ioredisClient.disconnect();- } catch {- // Ignore- }- }- }+ await closeRedisClients();process.env = originalEnv;});diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.tsindex 1b3917fd84..71cf1e0d7b 100644--- a/packages/data-provider/src/config.spec.ts+++ b/packages/data-provider/src/config.spec.ts@@ -1,6 +1,7 @@import type { TEndpointsConfig } from './types';import {allowedAddressesSchema,+ agentsEndpointSchema,bedrockModels,configSchema,excludedKeys,@@ -9,6 +10,7 @@ import {} from './config';import { EModelEndpoint, isDocumentSupportedProvider } from './schemas';import { getEndpointFileConfig, mergeFileConfig } from './file-config';+import { modelSpecSubagentsSchema } from './models';const endpointsConfig: TEndpointsConfig = {[EModelEndpoint.openAI]: { userProvide: false, order: 0 },@@ -20,6 +22,70 @@ const endpointsConfig: TEndpointsConfig = {Gemini: { type: EModelEndpoint.custom, userProvide: false, order: 9999 },};+describe('run-scoped subagent file sharing config', () => {+ it('preserves the opt-in default for existing configurations', () => {+ expect(agentsEndpointSchema.parse({}).fileSharing).toBeUndefined();+ expect(agentsEndpointSchema.parse({ fileSharing: {} }).fileSharing).toEqual({+ enabled: false,+ allowSiblingSharing: false,+ maxFiles: 100,+ maxPrivateBytes: 268_435_456,+ ttlMs: 3_600_000,+ });+ expect(modelSpecSubagentsSchema.parse({ enabled: true })).not.toHaveProperty('shareFiles');+ });++ it('retains explicit deployment and model-spec opt-ins through config parsing', () => {+ const result = configSchema.parse({+ version: '1.2.1',+ endpoints: {+ agents: {+ fileSharing: {+ enabled: true,+ allowSiblingSharing: true,+ maxFiles: 50,+ maxPrivateBytes: 16_777_216,+ ttlMs: 120_000,+ },+ },+ },+ modelSpecs: {+ list: [+ {+ name: 'file-team',+ label: 'File team',+ preset: { endpoint: EModelEndpoint.agents },+ subagents: { enabled: true, shareFiles: true },+ },+ ],+ },+ });+ expect(result.endpoints?.agents?.fileSharing).toEqual({+ enabled: true,+ allowSiblingSharing: true,+ maxFiles: 50,+ maxPrivateBytes: 16_777_216,+ ttlMs: 120_000,+ });+ expect(result.modelSpecs?.list[0].subagents?.shareFiles).toBe(true);+ expect(modelSpecSubagentsSchema.parse({ shareFiles: false }).shareFiles).toBe(false);+ });++ it.each([+ { maxFiles: 0 },+ { maxFiles: 1_001 },+ { maxFiles: 1.5 },+ { maxPrivateBytes: 0 },+ { maxPrivateBytes: 10_737_418_241 },+ { maxPrivateBytes: 1.5 },+ { ttlMs: 0 },+ { ttlMs: 86_400_001 },+ { ttlMs: 1.5 },+ ])('rejects invalid manifest limits: %j', (fileSharing) => {+ expect(agentsEndpointSchema.safeParse({ fileSharing }).success).toBe(false);+ });+});+describe('scheduled MCP preflight config', () => {it('bounds the separate readiness admission pool', () => {expect(diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex 3bd0bfaee5..2b52eadcbd 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -1201,6 +1201,23 @@ export const agentsEndpointSchema = baseEndpointSchema.max(MAX_SUBAGENTS_CEILING).optional().default(MAX_SUBAGENTS),+ /** Run-scoped file access for explicitly opted-in subagent delegations. */+ fileSharing: z+ .object({+ enabled: z.boolean().optional().default(false),+ allowSiblingSharing: z.boolean().optional().default(false),+ maxFiles: z.number().int().min(1).max(1_000).optional().default(100),+ /** Aggregate disk budget for private output versions retained during a run. */+ maxPrivateBytes: z+ .number()+ .int()+ .min(1)+ .max(10_737_418_240)+ .optional()+ .default(268_435_456),+ ttlMs: z.number().int().min(1).max(86_400_000).optional().default(3_600_000),+ })+ .optional(),/** Maximum concurrent Code API uploads per route and authenticated principal. */codeApiUploadConcurrency: z.number().int().min(1).max(100).optional().default(3),/** Maximum wall-clock time spent waiting on Code API rate limits per operation. */diff --git a/packages/data-provider/src/models.ts b/packages/data-provider/src/models.tsindex 17f14edef1..de7fb5d333 100644--- a/packages/data-provider/src/models.ts+++ b/packages/data-provider/src/models.ts@@ -88,6 +88,7 @@ export const modelSpecSubagentsSchema = z.object({enabled: z.boolean().optional(),allowSelf: z.boolean().optional(),+ shareFiles: z.boolean().optional(),agent_ids: z.array(z.string()).optional(),}).superRefine((subagents, ctx) => {diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.tsindex 00e17728eb..946d9bf57e 100644--- a/packages/data-provider/src/types.ts+++ b/packages/data-provider/src/types.ts@@ -15,7 +15,11 @@ import type {CodeWorkspaceOperation,CodeWorkspaceSelection,} from './code/workspace';-import type { CodeEnvironmentUserConfigSchema, CodeEnvironmentUserSettings } from './config';+import type {+ CodeEnvironmentUserConfigSchema,+ CodeEnvironmentUserSettings,+ TAgentsEndpoint,+} from './config';import type { Agent, EToolResources, StatefulCodeEnvironment } from './types/assistants';import type { CodeApprovalMode } from './code/approval';import type { RefillIntervalUnit } from './balance';@@ -632,6 +636,7 @@ export type TConfig = {};/** Effective subagents-per-agent cap served from `endpoints.agents.maxSubagents`. */maxSubagents?: number;+ fileSharing?: TAgentsEndpoint['fileSharing'];/** Concurrent Code API uploads allowed per route and authenticated principal. */codeApiUploadConcurrency?: number;/** Milliseconds one operation may spend waiting on Code API rate limits. */diff --git a/packages/data-provider/src/types/assistants.ts b/packages/data-provider/src/types/assistants.tsindex 3644a64e8c..4ddff9334d 100644--- a/packages/data-provider/src/types/assistants.ts+++ b/packages/data-provider/src/types/assistants.ts@@ -302,6 +302,8 @@ export type AgentSubagentsConfig = {enabled?: boolean;/** When true (default), the agent may spawn itself in an isolated context. */allowSelf?: boolean;+ /** Share current-turn files with authorized descendants. Off unless explicitly enabled. */+ shareFiles?: boolean;/** Specific agents that may be spawned as subagents. */agent_ids?: string[];/** Explicit saved-agent teams that may be spawned as bounded child graphs. */diff --git a/packages/data-provider/src/types/files.ts b/packages/data-provider/src/types/files.tsindex 32b21f9b32..3102c8ee72 100644--- a/packages/data-provider/src/types/files.ts+++ b/packages/data-provider/src/types/files.ts@@ -31,6 +31,7 @@ export enum FileContext {image_generation = 'image_generation',assistants_output = 'assistants_output',message_attachment = 'message_attachment',+ run_artifact = 'run_artifact',skill_file = 'skill_file',filename = 'filename',updatedAt = 'updatedAt',@@ -120,6 +121,19 @@ export type FileConfigInput = {legacyFileUploadUX?: boolean;};+/** The immutable origin of a file explicitly published from an agent execution. */+export type RunFileProvenance = {+ runId: string;+ executionId: string;+ agentId: string;+ parentExecutionId?: string;+ parentAgentId?: string;+ recipientAgentIds?: string[];+ sourceFileId: string;+ publishedAt: string;+ inputFileIds: string[];+};+export type TFile = {_id?: string;__v?: number;@@ -170,6 +184,7 @@ export type TFile = {*/previewError?: string;metadata?: {+ runFile?: RunFileProvenance;fileIdentifier?: string;/*** Structured form of `fileIdentifier`. Persisted alongside thediff --git a/packages/data-schemas/src/methods/file.commit.spec.ts b/packages/data-schemas/src/methods/file.commit.spec.tsnew file mode 100644index 0000000000..b487e62d08--- /dev/null+++ b/packages/data-schemas/src/methods/file.commit.spec.ts@@ -0,0 +1,217 @@+import mongoose from 'mongoose';+import { v4 as uuidv4 } from 'uuid';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { FileContext, FileSources } from 'librechat-data-provider';+import type { CodeFileCommitData, IMongoFile } from '~/types/file';+import { createFileMethods } from './file';+import fileSchema from '~/schema/file';++describe('Code output commits', () => {+ let mongo: MongoMemoryServer;+ let methods: ReturnType<typeof createFileMethods>;+ let File: mongoose.Model<IMongoFile>;+ const userId = new mongoose.Types.ObjectId().toString();++ function fileData(overrides: Partial<CodeFileCommitData> = {}): CodeFileCommitData {+ return {+ file_id: uuidv4(),+ user: userId,+ tenantId: 'tenant-a',+ conversationId: 'conversation-a',+ messageId: 'message-a',+ filename: 'report.csv',+ filepath: '/uploads/report.csv',+ bytes: 12,+ type: 'text/csv',+ source: FileSources.local,+ context: FileContext.execute_code,+ ...overrides,+ };+ }++ beforeAll(async () => {+ mongo = await MongoMemoryServer.create();+ await mongoose.connect(mongo.getUri());+ File = mongoose.model('File', fileSchema);+ await File.init();+ methods = createFileMethods(mongoose);+ });++ beforeEach(async () => {+ await File.deleteMany({});+ });++ afterAll(async () => {+ await mongoose.disconnect();+ mongoose.deleteModel('File');+ await mongo.stop();+ });++ it('creates foreground output without an upload TTL from plain file data', async () => {+ const data = fileData({+ createdAt: new Date('2026-09-12T10:00:00Z'),+ updatedAt: '2026-09-12T10:01:00Z',+ expiredAt: new Date('2026-09-19T10:00:00Z'),+ text: null,+ textFormat: null,+ status: null,+ previewError: null,+ previewRevision: null,+ });++ expect(await methods.commitCodeFile(data)).toBe(true);++ const stored = await File.findOne({ file_id: data.file_id }).lean();+ expect(stored?.user.toString()).toBe(userId);+ expect(stored).toMatchObject({+ file_id: data.file_id,+ filename: data.filename,+ filepath: data.filepath,+ messageId: data.messageId,+ expiredAt: data.expiredAt,+ text: null,+ textFormat: null,+ status: null,+ previewError: null,+ previewRevision: null,+ });+ expect(stored?.expiresAt).toBeUndefined();+ expect(stored?.createdAt).toBeInstanceOf(Date);+ });++ it('updates foreground output unconditionally and preserves existing upsert TTL semantics', async () => {+ const expiresAt = new Date(Date.now() + 3_600_000);+ const data = fileData({+ metadata: { sourceDispatchedAt: 200 },+ text: 'old preview',+ textFormat: 'html',+ status: 'ready',+ previewRevision: 'old-revision',+ });+ await File.create({ ...data, expiresAt });++ expect(+ await methods.commitCodeFile({+ ...data,+ filepath: '/uploads/foreground.csv',+ metadata: { sourceDispatchedAt: 100 },+ text: null,+ textFormat: null,+ status: null,+ previewRevision: null,+ }),+ ).toBe(true);++ const stored = await File.findOne({ file_id: data.file_id }).lean();+ expect(stored).toMatchObject({+ filepath: '/uploads/foreground.csv',+ metadata: { sourceDispatchedAt: 100 },+ text: null,+ textFormat: null,+ status: null,+ previewRevision: null,+ expiresAt,+ });+ expect(await File.countDocuments()).toBe(1);+ });++ it.each([+ ['absent', undefined],+ ['earlier', 100],+ ['equal', 200],+ ] as const)(+ 'commits over an %s dispatch stamp and removes the upload TTL',+ async (_label, stamp) => {+ const data = fileData({+ metadata: stamp == null ? undefined : { sourceDispatchedAt: stamp },+ });+ await File.create({ ...data, expiresAt: new Date(Date.now() + 3_600_000) });++ expect(+ await methods.commitCodeFile(+ {+ ...data,+ filepath: '/uploads/background.csv',+ metadata: { sourceDispatchedAt: 200 },+ },+ 200,+ ),+ ).toBe(true);++ const stored = await File.findOne({ file_id: data.file_id }).lean();+ expect(stored).toMatchObject({+ filepath: '/uploads/background.csv',+ metadata: { sourceDispatchedAt: 200 },+ });+ expect(stored?.expiresAt).toBeUndefined();+ },+ );++ it('rejects an output overtaken after its claim without changing the current bytes or TTL', async () => {+ const data = fileData();+ await methods.claimCodeFile({+ filename: data.filename,+ conversationId: data.conversationId!,+ file_id: data.file_id,+ user: userId,+ tenantId: data.tenantId,+ sourceDispatchedAt: 100,+ });+ const expiresAt = new Date(Date.now() + 3_600_000);+ await File.updateOne(+ { file_id: data.file_id },+ {+ $set: {+ filepath: '/uploads/newer.csv',+ 'metadata.sourceDispatchedAt': 200,+ expiresAt,+ },+ },+ );++ expect(+ await methods.commitCodeFile({ ...data, metadata: { sourceDispatchedAt: 100 } }, 100),+ ).toBe(false);++ expect(await File.findOne({ file_id: data.file_id }).lean()).toMatchObject({+ filepath: '/uploads/newer.csv',+ metadata: { sourceDispatchedAt: 200 },+ expiresAt,+ });+ });++ it.each([0, 200])(+ 'does not recreate an absent claimed row for dispatch stamp %s',+ async (stamp) => {+ expect(+ await methods.commitCodeFile(fileData({ metadata: { sourceDispatchedAt: stamp } }), stamp),+ ).toBe(false);+ expect(await File.countDocuments()).toBe(0);+ },+ );++ it('keeps the latest dispatch when competing background writes commit concurrently', async () => {+ const data = fileData({ metadata: { sourceDispatchedAt: 0 } });+ await File.create(data);++ const [, newer] = await Promise.all(+ [100, 200].map((stamp) =>+ methods.commitCodeFile(+ {+ ...data,+ filepath: `/uploads/${stamp}.csv`,+ metadata: { sourceDispatchedAt: stamp },+ },+ stamp,+ ),+ ),+ );++ expect(newer).toBe(true);+ expect(await File.findOne({ file_id: data.file_id }).lean()).toMatchObject({+ filepath: '/uploads/200.csv',+ metadata: { sourceDispatchedAt: 200 },+ });+ expect(await File.countDocuments()).toBe(1);+ });+});diff --git a/packages/data-schemas/src/methods/file.publication.spec.ts b/packages/data-schemas/src/methods/file.publication.spec.tsnew file mode 100644index 0000000000..66a6e6757a--- /dev/null+++ b/packages/data-schemas/src/methods/file.publication.spec.ts@@ -0,0 +1,266 @@+import mongoose from 'mongoose';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { FileContext, FileSources, isUUID } from 'librechat-data-provider';+import type { RunFileProvenance } from 'librechat-data-provider';+import type { RunArtifactContent, RunArtifactScope } from '~/types/file';+import { createFileMethods } from './file';+import fileSchema from '~/schema/file';++describe('Run artifact persistence', () => {+ let mongo: MongoMemoryServer;+ let methods: ReturnType<typeof createFileMethods>;+ const userId = new mongoose.Types.ObjectId().toString();+ const scope: RunArtifactScope = {+ userId,+ tenantId: 'tenant-a',+ conversationId: 'conversation-a',+ runId: 'run-a',+ executionId: 'child-a',+ agentId: 'agent-a',+ sourceFileId: 'sandbox-file-a',+ };++ const provenance = (identity: RunArtifactScope = scope): RunFileProvenance => ({+ runId: identity.runId,+ executionId: identity.executionId,+ agentId: identity.agentId,+ sourceFileId: identity.sourceFileId,+ parentExecutionId: 'parent-a',+ parentAgentId: 'parent-agent',+ recipientAgentIds: ['sibling-agent'],+ publishedAt: '2026-09-11T16:00:00.000Z',+ inputFileIds: ['input-pdf'],+ });++ const content = (filepath = '/uploads/attempt-a/report.csv'): RunArtifactContent => ({+ filename: 'report.csv',+ filepath,+ storageKey: filepath,+ bytes: 12,+ type: 'text/csv',+ source: FileSources.local,+ messageId: 'parent-response',+ text: 'a,b\n1,2',+ textFormat: 'text',+ metadata: {+ codeEnvRef: {+ kind: 'user',+ id: userId,+ file_id: scope.sourceFileId,+ storage_session_id: 'child-session',+ },+ },+ });++ beforeAll(async () => {+ mongo = await MongoMemoryServer.create();+ await mongoose.connect(mongo.getUri());+ mongoose.model('File', fileSchema);+ await mongoose.models.File.init();+ methods = createFileMethods(mongoose);+ });++ beforeEach(async () => {+ await mongoose.models.File.deleteMany({});+ });++ afterAll(async () => {+ await mongoose.disconnect();+ mongoose.deleteModel('File');+ await mongo.stop();+ });++ it('claims a stable UUID without exposing an incomplete file record', async () => {+ const [first, second] = await Promise.all([+ methods.claimRunArtifactFile(scope),+ methods.claimRunArtifactFile(scope),+ ]);+ expect(isUUID.parse(first.file_id)).toBe(first.file_id);+ expect(second).toEqual(first);+ expect(first.file).toBeUndefined();+ expect(await methods.listRunArtifacts(scope)).toEqual([]);+ expect(await mongoose.models.File.countDocuments()).toBe(0);+ });++ it('commits full provenance and storage together and returns plain owner identities', async () => {+ const claimed = await methods.claimRunArtifactFile(scope);+ const file = await methods.publishRunArtifactFile({+ scope,+ file: content(),+ provenance: provenance(),+ });+ expect(file).toMatchObject({+ file_id: claimed.file_id,+ user: userId,+ tenantId: scope.tenantId,+ conversationId: scope.conversationId,+ context: FileContext.run_artifact,+ filename: 'report.csv',+ filepath: content().filepath,+ metadata: { runFile: provenance(), destinationChosen: false },+ });+ expect(typeof file._id).toBe('string');+ expect(file.expiresAt).toBeUndefined();+ expect(file.metadata.codeEnvRef).toBeUndefined();+ expect(file.metadata.codeEnvRefs).toBeUndefined();+ expect(file.metadata.embeddedEntities).toBeUndefined();+ expect(await methods.claimRunArtifactFile(scope)).toEqual({ file_id: file.file_id, file });+ expect(await methods.listRunArtifacts(scope)).toEqual([file]);+ expect(await methods.getRunFileCandidates([file.file_id], scope.tenantId)).toEqual([file]);+ expect((await methods.getRunFileCandidates([file.file_id], scope.tenantId))[0].text).toBe(+ 'a,b\n1,2',+ );+ });++ it('preserves the first committed bytes and grants across concurrent publication retries', async () => {+ const published = await Promise.all(+ Array.from({ length: 8 }, (_, index) =>+ methods.publishRunArtifactFile({+ scope,+ file: content(`/uploads/attempt-${index}/report.csv`),+ provenance: {+ ...provenance(),+ recipientAgentIds: [`recipient-${index}`],+ },+ }),+ ),+ );+ expect(new Set(published.map((file) => file.file_id)).size).toBe(1);+ expect(new Set(published.map((file) => file.filepath)).size).toBe(1);+ expect(+ new Set(published.map((file) => file.metadata.runFile.recipientAgentIds?.[0])).size,+ ).toBe(1);+ expect(await mongoose.models.File.countDocuments()).toBe(1);+ const retry = await methods.publishRunArtifactFile({+ scope,+ file: content('/uploads/later-attempt/other.csv'),+ provenance: {+ ...provenance(),+ recipientAgentIds: ['new-recipient'],+ parentAgentId: 'different-parent',+ },+ });+ expect(retry).toEqual(published[0]);+ });++ it('loads setup candidates only from the authenticated tenant while preserving shared ownership', async () => {+ const otherOwner = new mongoose.Types.ObjectId().toString();+ const candidates = [+ { file_id: 'owned', tenantId: 'tenant-a', user: userId },+ { file_id: 'shared', tenantId: 'tenant-a', user: otherOwner },+ { file_id: 'foreign-tenant', tenantId: 'tenant-b', user: userId },+ { file_id: 'legacy-missing', user: userId },+ { file_id: 'legacy-null', tenantId: null, user: userId },+ ];+ await mongoose.models.File.create(+ candidates.map((candidate) => ({+ ...content(),+ context: FileContext.agents,+ ...candidate,+ })),+ );+ const ids = candidates.map((candidate) => candidate.file_id);+ expect(+ (await methods.getRunFileCandidates(ids, 'tenant-a')).map((file) => file.file_id).sort(),+ ).toEqual(['owned', 'shared']);+ expect((await methods.getRunFileCandidates(ids)).map((file) => file.file_id).sort()).toEqual([+ 'legacy-missing',+ 'legacy-null',+ ]);+ expect(+ (await methods.getRunFileCandidates(ids, null)).map((file) => file.file_id).sort(),+ ).toEqual(['legacy-missing', 'legacy-null']);+ });++ it('keeps same-named child outputs separate from each other and ordinary code files', async () => {+ await methods.claimCodeFile({+ filename: 'report.csv',+ conversationId: scope.conversationId,+ file_id: 'ordinary-code-file',+ user: userId,+ tenantId: scope.tenantId,+ });+ const childScopes = [scope, { ...scope, executionId: 'child-b' }];+ const files = await Promise.all(+ childScopes.map((identity) =>+ methods.publishRunArtifactFile({+ scope: identity,+ file: content(),+ provenance: provenance(identity),+ }),+ ),+ );+ expect(files[0].file_id).not.toBe(files[1].file_id);+ expect(files.map((file) => file.filename)).toEqual(['report.csv', 'report.csv']);+ expect(await mongoose.models.File.countDocuments()).toBe(3);+ expect(await methods.listRunArtifacts(scope)).toHaveLength(2);+ });++ it.each([+ { userId: new mongoose.Types.ObjectId().toString() },+ { tenantId: 'tenant-b' },+ { tenantId: undefined },+ { conversationId: 'conversation-b' },+ { runId: 'run-b' },+ ])('cannot load a publication through a different owner scope: %o', async (difference) => {+ await methods.publishRunArtifactFile({ scope, file: content(), provenance: provenance() });+ const foreign = { ...scope, ...difference };+ expect(await methods.findRunArtifactFile(foreign)).toBeNull();+ expect(await methods.listRunArtifacts(foreign)).toEqual([]);+ expect((await methods.claimRunArtifactFile(foreign)).file_id).not.toBe(+ (await methods.claimRunArtifactFile(scope)).file_id,+ );+ });++ it('isolates graph members with the same execution and source file id', async () => {+ const peer = { ...scope, agentId: 'other-graph-member' };+ const [first, second] = await Promise.all(+ [scope, peer].map((identity) =>+ methods.publishRunArtifactFile({+ scope: identity,+ file: content(`/uploads/${identity.agentId}/report.csv`),+ provenance: provenance(identity),+ }),+ ),+ );+ expect(first.file_id).not.toBe(second.file_id);+ expect(await methods.findRunArtifactFile(scope)).toEqual(first);+ expect(await methods.findRunArtifactFile(peer)).toEqual(second);+ expect(await methods.listRunArtifacts(scope)).toHaveLength(2);+ });++ it('does not load another producing agent or accept mismatched provenance', async () => {+ await methods.publishRunArtifactFile({ scope, file: content(), provenance: provenance() });+ expect(await methods.findRunArtifactFile({ ...scope, agentId: 'other-agent' })).toBeNull();+ await expect(+ methods.publishRunArtifactFile({+ scope,+ file: content(),+ provenance: { ...provenance(), runId: 'other-run' },+ }),+ ).rejects.toThrow('provenance');+ });++ it('rejects transient download fallbacks and retains storage cleanup deadlines', async () => {+ await expect(+ methods.publishRunArtifactFile({+ scope,+ file: { ...content(), source: FileSources.execute_code },+ provenance: provenance(),+ }),+ ).rejects.toThrow('durable stored file');+ expect(await methods.listRunArtifacts(scope)).toEqual([]);+ const expiredAt = new Date('2026-12-01T00:00:00.000Z');+ const file = await methods.publishRunArtifactFile({+ scope,+ file: { ...content(), expiredAt },+ provenance: provenance(),+ });+ expect(file.expiredAt).toEqual(expiredAt);+ expect(+ (await methods.getExpiredFiles(10, { now: new Date('2026-12-02T00:00:00.000Z') })).map(+ (expired) => expired.file_id,+ ),+ ).toEqual([file.file_id]);+ });+});diff --git a/packages/data-schemas/src/methods/file.ts b/packages/data-schemas/src/methods/file.tsindex 4b262ff06d..7e0993bc13 100644--- a/packages/data-schemas/src/methods/file.ts+++ b/packages/data-schemas/src/methods/file.ts@@ -1,7 +1,16 @@-import { EToolResources, FileContext } from 'librechat-data-provider';+import { createHash } from 'crypto';+import { EToolResources, FileContext, FileSources } from 'librechat-data-provider';+import type { CodeEnvRef, TFile } from 'librechat-data-provider';import type { FilterQuery, SortOrder, Model } from 'mongoose';-import type { CodeEnvRef } from 'librechat-data-provider';-import type { IMongoFile } from '~/types/file';+import type {+ IMongoFile,+ RunArtifactFile,+ RunArtifactClaim,+ RunArtifactScope,+ CodeFileCommitData,+ RunArtifactRunScope,+ PublishRunArtifactInput,+} from '~/types/file';import { tenantSafeBulkWrite } from '~/utils/tenantBulkWrite';import logger from '../config/winston';@@ -38,8 +47,88 @@ function withOwnerScope<T extends FilterQuery<IMongoFile>>(return scopedFilter;}+type PlainFileDocument = Omit<TFile, 'user' | '_id'> & {+ user: IMongoFile['user'];+ _id?: IMongoFile['_id'];+};++type RunArtifactDocument = Omit<RunArtifactFile, 'user' | '_id'> & PlainFileDocument;++function runArtifactFilter(scope: RunArtifactRunScope): FilterQuery<IMongoFile> {+ const required = [scope.userId, scope.conversationId, scope.runId];+ if (required.some((value) => typeof value !== 'string' || value.trim().length === 0)) {+ throw new Error('A complete run artifact owner scope is required');+ }+ if (scope.tenantId != null && scope.tenantId.trim().length === 0) {+ throw new Error('An empty run artifact tenant is invalid');+ }+ return {+ user: scope.userId,+ tenantId: scope.tenantId ?? null,+ conversationId: scope.conversationId,+ context: FileContext.run_artifact,+ 'metadata.runFile.runId': scope.runId,+ };+}++function runArtifactIdentityFilter(scope: RunArtifactScope): FilterQuery<IMongoFile> {+ const filter = runArtifactFilter(scope);+ if (+ [scope.executionId, scope.agentId, scope.sourceFileId].some(+ (value) => typeof value !== 'string' || value.trim().length === 0,+ )+ ) {+ throw new Error('A complete run artifact execution scope is required');+ }+ return {+ ...filter,+ 'metadata.runFile.executionId': scope.executionId,+ 'metadata.runFile.agentId': scope.agentId,+ 'metadata.runFile.sourceFileId': scope.sourceFileId,+ };+}++/** A versioned, scoped UUID reserves no incomplete file document or downloadable bytes. */+function runArtifactFileId(scope: RunArtifactScope): string {+ const bytes = createHash('sha256')+ .update(+ JSON.stringify([+ 'librechat-run-artifact:v1',+ scope.userId,+ scope.tenantId ?? null,+ scope.conversationId,+ scope.runId,+ scope.executionId,+ scope.agentId,+ scope.sourceFileId,+ ]),+ )+ .digest()+ .subarray(0, 16);+ bytes[6] = (bytes[6] & 0x0f) | 0x80;+ bytes[8] = (bytes[8] & 0x3f) | 0x80;+ const hex = bytes.toString('hex');+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;+}++function serializeRunArtifact(+ file: RunArtifactDocument,+ scope?: RunArtifactScope,+): RunArtifactFile {+ if (scope != null && file.metadata.runFile.agentId !== scope.agentId) {+ throw new Error('The run artifact belongs to a different producing agent');+ }+ const { _id, user, ...fields } = file;+ return { ...fields, user: user.toString(), ...(_id == null ? {} : { _id: String(_id) }) };+}+/** Factory function that takes mongoose instance and returns the file methods */export function createFileMethods(mongoose: typeof import('mongoose')): {+ getRunFileCandidates: (fileIds: readonly string[], tenantId?: string | null) => Promise<TFile[]>;+ claimRunArtifactFile: (scope: RunArtifactScope) => Promise<RunArtifactClaim>;+ publishRunArtifactFile: (input: PublishRunArtifactInput) => Promise<RunArtifactFile>;+ findRunArtifactFile: (scope: RunArtifactScope) => Promise<RunArtifactFile | null>;+ listRunArtifacts: (scope: RunArtifactRunScope) => Promise<RunArtifactFile[]>;findFileById: (file_id: string, options?: Record<string, unknown>) => Promise<IMongoFile | null>;getFiles: (filter: FilterQuery<IMongoFile>,@@ -79,6 +168,7 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {tenantId?: string | null;sourceDispatchedAt?: number;}) => Promise<IMongoFile>;+ commitCodeFile: (data: CodeFileCommitData, sourceDispatchedAt?: number) => Promise<boolean>;createFile: (data: Partial<IMongoFile>, disableTTL?: boolean) => Promise<IMongoFile | null>;updateFile: (data: Partial<IMongoFile> & { file_id: string },@@ -123,6 +213,134 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {) => Promise<number>;sweepOrphanedPreviews: (maxAgeMs?: number) => Promise<number>;} {+ /** Hydrates only host-selected IDs; the caller applies its existing agent-file authorization. */+ async function getRunFileCandidates(+ fileIds: readonly string[],+ tenantId?: string | null,+ ): Promise<TFile[]> {+ if (fileIds.length === 0) {+ return [];+ }+ const File = mongoose.models.File as Model<IMongoFile>;+ const files = await File.find({+ file_id: { $in: fileIds },+ tenantId: tenantId ?? null,+ }).lean<PlainFileDocument[]>();+ return files.map(({ user, _id, ...file }) => ({+ ...file,+ user: String(user),+ embedded: file.embedded === true,+ ...(_id == null ? {} : { _id: String(_id) }),+ }));+ }++ async function findRunArtifactFile(scope: RunArtifactScope): Promise<RunArtifactFile | null> {+ const File = mongoose.models.File as Model<IMongoFile>;+ const file = await File.findOne(runArtifactIdentityFilter(scope)).lean<RunArtifactDocument>();+ return file == null ? null : serializeRunArtifact(file, scope);+ }++ async function listRunArtifacts(scope: RunArtifactRunScope): Promise<RunArtifactFile[]> {+ const File = mongoose.models.File as Model<IMongoFile>;+ const files = await File.find(runArtifactFilter(scope))+ .sort({ createdAt: 1, file_id: 1 })+ .lean<RunArtifactDocument[]>();+ return files.map((file) => serializeRunArtifact(file));+ }++ async function claimRunArtifactFile(scope: RunArtifactScope): Promise<RunArtifactClaim> {+ const file = await findRunArtifactFile(scope);+ return file == null ? { file_id: runArtifactFileId(scope) } : { file_id: file.file_id, file };+ }++ /** Publishes one complete storage result. Retried writers cannot replace its bytes or grants. */+ async function publishRunArtifactFile({+ scope,+ file,+ provenance,+ }: PublishRunArtifactInput): Promise<RunArtifactFile> {+ const File = mongoose.models.File as Model<IMongoFile>;+ const filter = runArtifactIdentityFilter(scope);+ if (+ provenance.runId !== scope.runId ||+ provenance.executionId !== scope.executionId ||+ provenance.agentId !== scope.agentId ||+ provenance.sourceFileId !== scope.sourceFileId ||+ !Number.isFinite(Date.parse(provenance.publishedAt))+ ) {+ throw new Error('Run artifact provenance does not match its publication scope');+ }+ if (+ !file.filepath ||+ !file.filename ||+ !file.type ||+ file.source === FileSources.execute_code ||+ !Number.isSafeInteger(file.bytes) ||+ file.bytes < 0+ ) {+ throw new Error('A durable stored file is required to publish a run artifact');+ }+ const now = new Date();+ const insert = {+ filename: file.filename,+ filepath: file.filepath,+ bytes: file.bytes,+ type: file.type,+ storageKey: file.storageKey,+ storageRegion: file.storageRegion,+ text: file.text,+ textFormat: file.textFormat,+ status: file.status,+ previewError: file.previewError,+ previewRevision: file.previewRevision,+ width: file.width,+ height: file.height,+ messageId: file.messageId,+ expiredAt: file.expiredAt,+ file_id: runArtifactFileId(scope),+ user: scope.userId,+ tenantId: scope.tenantId ?? undefined,+ conversationId: scope.conversationId,+ context: FileContext.run_artifact,+ object: 'file',+ source: file.source ?? FileSources.local,+ embedded: false,+ usage: 1,+ llmDeliveryPath: file.llmDeliveryPath ?? 'none',+ metadata: {+ ...file.metadata,+ // The source is a private execution object. Consumers must provision the+ // immutable durable copy, never reuse that potentially mutable source.+ codeEnvRef: undefined,+ codeEnvRefs: undefined,+ embeddedEntities: undefined,+ destinationChosen: false,+ runFile: provenance,+ },+ createdAt: now,+ updatedAt: now,+ };+ try {+ const published = await File.findOneAndUpdate(+ filter,+ { $setOnInsert: insert },+ { upsert: true, new: true, runValidators: true, timestamps: false },+ ).lean<RunArtifactDocument>();+ if (published == null) {+ throw new Error('Run artifact publication did not produce a file');+ }+ return serializeRunArtifact(published, scope);+ } catch (error) {+ if (error instanceof Error && 'code' in error && error.code === 11000) {+ const existing = await findRunArtifactFile(scope);+ if (existing != null) {+ return existing;+ }+ }+ throw error;+ }+ }+/*** Finds a file by its file_id with additional query options.* @param file_id - The unique identifier of the file@@ -592,11 +810,11 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {* @returns A promise that resolves to the created file document*/async function createFile(- data: Partial<IMongoFile>,+ data: Partial<IMongoFile> | CodeFileCommitData,disableTTL?: boolean,): Promise<IMongoFile | null> {const File = mongoose.models.File as Model<IMongoFile>;- const fileData: Partial<IMongoFile> = {+ const fileData: (Partial<IMongoFile> | CodeFileCommitData) & { expiresAt?: Date } = {...data,expiresAt: new Date(Date.now() + 3600 * 1000),};@@ -629,7 +847,7 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {* deleted).*/async function updateFile(- data: Partial<IMongoFile> & { file_id: string },+ data: (Partial<IMongoFile> & { file_id: string }) | CodeFileCommitData,extraFilter?: FilterQuery<IMongoFile>,): Promise<IMongoFile | null> {const File = mongoose.models.File as Model<IMongoFile>;@@ -644,6 +862,24 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {}).lean<IMongoFile>();}+ /** Background outputs commit only while their dispatch still owns the claimed filename. */+ async function commitCodeFile(+ data: CodeFileCommitData,+ sourceDispatchedAt?: number,+ ): Promise<boolean> {+ if (sourceDispatchedAt == null) {+ await createFile(data, true);+ return true;+ }+ const committed = await updateFile(data, {+ $or: [+ { 'metadata.sourceDispatchedAt': { $exists: false } },+ { 'metadata.sourceDispatchedAt': { $lte: sourceDispatchedAt } },+ ],+ });+ return committed != null;+ }+/*** Records one code-environment route pointer without rewriting the rest of `metadata`.* Agents provisioning the same file to different deployments write concurrently, and a@@ -964,6 +1200,11 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {}return {+ getRunFileCandidates,+ claimRunArtifactFile,+ publishRunArtifactFile,+ findRunArtifactFile,+ listRunArtifacts,findFileById,getFiles,getExpiredFiles,@@ -974,6 +1215,7 @@ export function createFileMethods(mongoose: typeof import('mongoose')): {getUserCodeFiles,getDeferredProvisionFiles,claimCodeFile,+ commitCodeFile,createFile,updateFile,updateFileCodeEnvRef,diff --git a/packages/data-schemas/src/schema/file.ts b/packages/data-schemas/src/schema/file.tsindex 9941b590a4..5825ac6cb0 100644--- a/packages/data-schemas/src/schema/file.ts+++ b/packages/data-schemas/src/schema/file.ts@@ -1,8 +1,24 @@import mongoose, { Schema } from 'mongoose';import { FileContext, FileSources } from 'librechat-data-provider';+import type { RunFileProvenance } from 'librechat-data-provider';import type { IMongoFile } from '~/types';import { codeEnvRefMapSchema, codeEnvRefSchema } from './codeEnvRef';+const runFileProvenanceSchema = new Schema<RunFileProvenance>(+ {+ runId: { type: String, required: true },+ executionId: { type: String, required: true },+ agentId: { type: String, required: true },+ parentExecutionId: { type: String },+ parentAgentId: { type: String },+ recipientAgentIds: { type: [String], default: undefined },+ sourceFileId: { type: String, required: true },+ publishedAt: { type: String, required: true },+ inputFileIds: { type: [String], required: true },+ },+ { _id: false },+);+const file: Schema<IMongoFile> = new Schema({user: {@@ -119,6 +135,11 @@ const file: Schema<IMongoFile> = new Schema(width: Number,height: Number,metadata: {+ runFile: {+ type: runFileProvenanceSchema,+ default: undefined,+ immutable: true,+ },codeEnvRef: {type: codeEnvRefSchema,default: undefined,@@ -204,5 +225,21 @@ file.index({ filename: 1, conversationId: 1, context: 1, tenantId: 1 },{ unique: true, partialFilterExpression: { context: FileContext.execute_code } },);+file.index(+ {+ user: 1,+ tenantId: 1,+ conversationId: 1,+ 'metadata.runFile.runId': 1,+ 'metadata.runFile.executionId': 1,+ 'metadata.runFile.agentId': 1,+ 'metadata.runFile.sourceFileId': 1,+ },+ {+ name: 'run_artifact_identity',+ unique: true,+ partialFilterExpression: { context: FileContext.run_artifact },+ },+);export default file;diff --git a/packages/data-schemas/src/types/file.ts b/packages/data-schemas/src/types/file.tsindex bb4e71dd81..012f9bbb07 100644--- a/packages/data-schemas/src/types/file.ts+++ b/packages/data-schemas/src/types/file.ts@@ -1,5 +1,86 @@import { Document, Types } from 'mongoose';-import type { CodeEnvRef, CodeEnvRefMap } from 'librechat-data-provider';+import type {+ CodeEnvRef,+ CodeEnvRefMap,+ FileContext,+ RunFileProvenance,+ TFile,+} from 'librechat-data-provider';++export type RunArtifactRunScope = {+ userId: string;+ tenantId?: string | null;+ conversationId: string;+ runId: string;+};++export type RunArtifactScope = RunArtifactRunScope & {+ executionId: string;+ agentId: string;+ sourceFileId: string;+};++export type RunArtifactFile = TFile & {+ conversationId: string;+ messageId?: string;+ expiredAt?: Date | null;+ previewRevision?: string;+ metadata: NonNullable<TFile['metadata']> & { runFile: RunFileProvenance };+};++export type RunArtifactContent = Pick<+ TFile,+ | 'filename'+ | 'filepath'+ | 'bytes'+ | 'type'+ | 'source'+ | 'storageKey'+ | 'storageRegion'+ | 'text'+ | 'textFormat'+ | 'width'+ | 'height'+ | 'status'+ | 'previewError'+ | 'llmDeliveryPath'+> & {+ messageId?: string;+ expiredAt?: Date | null;+ previewRevision?: string;+ metadata?: Omit<NonNullable<TFile['metadata']>, 'runFile'>;+};++export type CodeFileCommitData = Omit<+ RunArtifactContent,+ 'text' | 'status' | 'previewError' | 'previewRevision'+> & {+ file_id: string;+ user: string;+ tenantId?: string;+ conversationId?: string;+ context?: FileContext;+ object?: 'file';+ embedded?: boolean;+ usage?: number;+ text?: string | null;+ status?: TFile['status'] | null;+ previewError?: string | null;+ previewRevision?: string | null;+ createdAt?: Date | string;+ updatedAt?: Date | string;+};++export type PublishRunArtifactInput = {+ scope: RunArtifactScope;+ file: RunArtifactContent;+ provenance: RunFileProvenance;+};++export type RunArtifactClaim = {+ file_id: string;+ file?: RunArtifactFile;+};export interface IMongoFile extends Omit<Document, 'model'> {user: Types.ObjectId;@@ -63,6 +144,7 @@ export interface IMongoFile extends Omit<Document, 'model'> {width?: number;height?: number;metadata?: {+ runFile?: RunFileProvenance;/*** Code-environment cache pointer for files re-uploadable to* codeapi (chat attachments, agent tool resources, code-output