Skip to content

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

🎒 fix: Bound Agent Attachment Context (#15694)

Danny Avilae370ce4b21ea
diff --git a/api/app/clients/BaseClient.js b/api/app/clients/BaseClient.js
index f366c6d253..24e5d0af3d 100644
--- a/api/app/clients/BaseClient.js
+++ b/api/app/clients/BaseClient.js
@@ -18,6 +18,7 @@ const {
assertModelBoundProviderContent,
collectModelBoundHistoricalFileIdState,
projectModelBoundSourceFiles,
+ isModelBoundAttachmentFile,
} = require('@librechat/api');
const {
Constants,
@@ -1173,46 +1174,48 @@ class BaseClient {
parentMessageId,
mapMethod,
});
+ if (this.shouldSummarize) {
+ for (let i = _messages.length - 1; i >= 0; i--) {
+ const msg = _messages[i];
+ if (!msg) {
+ continue;
+ }
- _messages = await this.addPreviousAttachments(_messages);
-
- if (!this.shouldSummarize) {
- return _messages;
- }
+ const summaryBlock = BaseClient.findSummaryContentBlock(msg);
+ if (summaryBlock) {
+ this.previous_summary = {
+ ...msg,
+ summary: BaseClient.getSummaryText(summaryBlock),
+ summaryTokenCount: summaryBlock.tokenCount,
+ };
+ break;
+ }
- for (let i = _messages.length - 1; i >= 0; i--) {
- const msg = _messages[i];
- if (!msg) {
- continue;
+ if (msg.summary) {
+ this.previous_summary = msg;
+ break;
+ }
}
- const summaryBlock = BaseClient.findSummaryContentBlock(msg);
- if (summaryBlock) {
- this.previous_summary = {
- ...msg,
- summary: BaseClient.getSummaryText(summaryBlock),
- summaryTokenCount: summaryBlock.tokenCount,
- };
- break;
- }
+ _messages = this.constructor.getMessagesForConversation({
+ messages,
+ parentMessageId,
+ mapMethod,
+ summary: true,
+ });
- if (msg.summary) {
- this.previous_summary = msg;
- break;
+ if (this.previous_summary) {
+ const { messageId, summary, tokenCount, summaryTokenCount } = this.previous_summary;
+ logger.debug('[BaseClient] Previous summary:', {
+ messageId,
+ summary,
+ tokenCount,
+ summaryTokenCount,
+ });
}
}
- if (this.previous_summary) {
- const { messageId, summary, tokenCount, summaryTokenCount } = this.previous_summary;
- logger.debug('[BaseClient] Previous summary:', {
- messageId,
- summary,
- tokenCount,
- summaryTokenCount,
- });
- }
-
- return _messages;
+ return this.addPreviousAttachments(_messages);
}
/**
@@ -1831,14 +1834,66 @@ class BaseClient {
historicalFileState.fileIds,
this.options.req?.user,
);
+ const nonSteerReplayFileIds = collectModelBoundHistoricalFileIdState(
+ _messages.map((message) => ({
+ files: message.files,
+ content: Array.isArray(message.content)
+ ? message.content.filter((part) => part?.type !== ContentTypes.STEER)
+ : message.content,
+ })),
+ ).fileIds.filter((fileId) => !contextSeen.has(fileId));
+ const steerReplayFileIds = [];
+ for (const message of _messages) {
+ if (!Array.isArray(message?.content)) {
+ continue;
+ }
+ for (const part of message.content) {
+ if (part?.type !== ContentTypes.STEER || !Array.isArray(part.files)) {
+ continue;
+ }
+ for (const file of part.files) {
+ if (typeof file?.file_id === 'string' && file.file_id.length > 0) {
+ steerReplayFileIds.push(file.file_id);
+ }
+ }
+ }
+ }
for (const file of files) {
if (file?.file_id) {
authorizedFilesById.set(file.file_id, file);
}
}
+ let admittedHistoricalFileIds;
+ if (typeof this.assertHistoricalAttachmentLimits === 'function') {
+ const admittedHistoricalFiles = await this.assertHistoricalAttachmentLimits(
+ [...nonSteerReplayFileIds, ...steerReplayFileIds]
+ .map((fileId) => authorizedFilesById.get(fileId))
+ .filter((file) => file != null && isModelBoundAttachmentFile(file)),
+ );
+ admittedHistoricalFileIds = new Set(
+ (admittedHistoricalFiles ?? []).map((file) => file?.file_id).filter(Boolean),
+ );
+ }
+ this.modelBoundHistoricalSteerFiles = steerReplayFileIds
+ .map((fileId) => authorizedFilesById.get(fileId))
+ .filter(
+ (file) =>
+ file != null &&
+ isModelBoundAttachmentFile(file) &&
+ (!admittedHistoricalFileIds || admittedHistoricalFileIds.has(file.file_id)),
+ );
/** Owner-scoped docs for THIS turn, including steer-part refs — the steer
* replay stamp consumes this instead of issuing a second query. */
this.authorizedHistoricalFiles = authorizedFilesById;
+ this.authorizedHistoricalReplayFiles = new Map(
+ files
+ .filter(
+ (file) =>
+ file?.file_id &&
+ (!admittedHistoricalFileIds || admittedHistoricalFileIds.has(file.file_id)),
+ )
+ .map((file) => [file.file_id, file]),
+ );
/**
*
@@ -1859,7 +1914,10 @@ class BaseClient {
continue;
}
const authorizedFile = authorizedFilesById.get(file.file_id);
- if (authorizedFile) {
+ if (
+ authorizedFile &&
+ (!admittedHistoricalFileIds || admittedHistoricalFileIds.has(file.file_id))
+ ) {
contextFiles.push(authorizedFile);
contextSeen.add(file.file_id);
}
@@ -1890,12 +1948,17 @@ class BaseClient {
return message;
}
- await Promise.all([
+ const [, processedFiles] = await Promise.all([
this.addFileContextToMessage(message, contextFiles),
this.processAttachments(message, contextFiles),
]);
- this.message_file_map[message.messageId] = contextFiles;
+ const processedFileIds = new Set(
+ (processedFiles ?? []).map((file) => file?.file_id).filter(Boolean),
+ );
+ this.message_file_map[message.messageId] = contextFiles.filter(
+ (file) => processedFileIds.has(file?.file_id) && isModelBoundAttachmentFile(file),
+ );
return message;
};
diff --git a/api/app/clients/specs/BaseClient.test.js b/api/app/clients/specs/BaseClient.test.js
index 92a96eb649..ef1a17c066 100644
--- a/api/app/clients/specs/BaseClient.test.js
+++ b/api/app/clients/specs/BaseClient.test.js
@@ -278,6 +278,36 @@ describe('BaseClient', () => {
expect(getMessages).toHaveBeenCalledTimes(1);
expect(result.map((m) => m.messageId)).toEqual(['root', 'reply']);
});
+
+ test('prunes pre-summary history before hydrating attachments', async () => {
+ const addPreviousAttachments = jest.fn(async (messages) => messages);
+ receiver.shouldSummarize = true;
+ receiver.addPreviousAttachments = addPreviousAttachments;
+ getMessages.mockResolvedValueOnce([
+ {
+ messageId: 'pre-summary',
+ parentMessageId: Constants.NO_PARENT,
+ files: [{ file_id: 'old-file' }],
+ },
+ {
+ messageId: 'summary',
+ parentMessageId: 'pre-summary',
+ summary: 'Earlier context',
+ summaryTokenCount: 10,
+ },
+ { messageId: 'latest', parentMessageId: 'summary', text: 'Continue' },
+ ]);
+
+ const result = await loadHistory('latest');
+
+ expect(result.map((message) => message.messageId)).toEqual(['summary', 'latest']);
+ expect(addPreviousAttachments).toHaveBeenCalledWith(
+ expect.not.arrayContaining([expect.objectContaining({ messageId: 'pre-summary' })]),
+ );
+ receiver.shouldSummarize = false;
+ receiver.addPreviousAttachments = async (messages) => messages;
+ receiver.previous_summary = undefined;
+ });
});
describe('getMessagesForConversation', () => {
@@ -2443,6 +2473,7 @@ describe('BaseClient', () => {
}
});
TestClient.processAttachments = jest.fn(async (_message, files) => files);
+ TestClient.assertHistoricalAttachmentLimits = undefined;
TestClient.checkVisionRequest = jest.fn();
});
@@ -2717,7 +2748,7 @@ describe('BaseClient', () => {
const [message] = await messagesPromise;
expect(message.fileContext).toBe('authorized owner text');
- expect(TestClient.message_file_map['msg-concurrent-file-work']).toEqual([ownerFile]);
+ expect(TestClient.message_file_map['msg-concurrent-file-work']).toEqual([]);
});
test('preserves download-only historical attachments without trusting file fields', async () => {
@@ -2758,6 +2789,92 @@ describe('BaseClient', () => {
expect(JSON.stringify(message)).not.toContain('victim');
});
+ test('processes only historical files admitted by the runtime endpoint policy', async () => {
+ const modelFile = { ...ownerFile, metadata: undefined };
+ getFiles.mockResolvedValueOnce([modelFile]);
+ TestClient.assertHistoricalAttachmentLimits = jest.fn(async () => []);
+
+ const [message] = await TestClient.addPreviousAttachments([
+ {
+ messageId: 'msg-1',
+ text: 'Use the attachment',
+ files: [{ file_id: modelFile.file_id }],
+ },
+ ]);
+
+ expect(TestClient.assertHistoricalAttachmentLimits).toHaveBeenCalledWith([modelFile]);
+ expect(TestClient.addFileContextToMessage).not.toHaveBeenCalled();
+ expect(TestClient.processAttachments).not.toHaveBeenCalled();
+ expect(message.files).toEqual([expect.objectContaining({ file_id: modelFile.file_id })]);
+ });
+
+ test('includes nested steer file references in historical admission', async () => {
+ const modelFile = { ...ownerFile, metadata: undefined };
+ getFiles.mockResolvedValueOnce([modelFile]);
+ TestClient.assertHistoricalAttachmentLimits = jest.fn(async (files) => files);
+
+ await TestClient.addPreviousAttachments([
+ {
+ messageId: 'msg-steer',
+ content: [
+ {
+ type: 'steer',
+ steer: 'Use the attachment',
+ files: [{ file_id: modelFile.file_id }],
+ },
+ ],
+ },
+ ]);
+
+ expect(TestClient.assertHistoricalAttachmentLimits).toHaveBeenCalledWith([modelFile]);
+ expect(TestClient.authorizedHistoricalReplayFiles.get(modelFile.file_id)).toEqual(modelFile);
+ });
+
+ test('preserves repeated steer file injections in historical admission', async () => {
+ const modelFile = { ...ownerFile, metadata: undefined };
+ getFiles.mockResolvedValueOnce([modelFile]);
+ TestClient.assertHistoricalAttachmentLimits = jest.fn(async (files) => files);
+
+ await TestClient.addPreviousAttachments([
+ {
+ messageId: 'msg-steer-repeat',
+ content: [
+ {
+ type: 'steer',
+ steer: 'Use the attachment once.',
+ files: [{ file_id: modelFile.file_id }],
+ },
+ {
+ type: 'steer',
+ steer: 'Use the attachment again.',
+ files: [{ file_id: modelFile.file_id }],
+ },
+ ],
+ },
+ ]);
+
+ expect(TestClient.assertHistoricalAttachmentLimits).toHaveBeenCalledWith([
+ modelFile,
+ modelFile,
+ ]);
+ expect(TestClient.modelBoundHistoricalSteerFiles).toEqual([modelFile, modelFile]);
+ });
+
+ test('keeps canonical byte metadata for processed historical survivors', async () => {
+ const modelFile = { ...ownerFile, metadata: undefined, bytes: 120 * 1024 * 1024 };
+ getFiles.mockResolvedValueOnce([modelFile]);
+ TestClient.processAttachments.mockResolvedValue([{ file_id: modelFile.file_id }]);
+
+ await TestClient.addPreviousAttachments([
+ {
+ messageId: 'msg-canonical-bytes',
+ files: [{ file_id: modelFile.file_id }],
+ },
+ ]);
+
+ expect(TestClient.message_file_map['msg-canonical-bytes']).toEqual([modelFile]);
+ });
+
test('merges safe per-message metadata onto authorized DB-backed attachments', async () => {
getFiles.mockResolvedValueOnce([ownerFile]);
diff --git a/api/server/controllers/agents/__tests__/client.steerWiring.spec.js b/api/server/controllers/agents/__tests__/client.steerWiring.spec.js
index f599d14b1e..49de2951e0 100644
--- a/api/server/controllers/agents/__tests__/client.steerWiring.spec.js
+++ b/api/server/controllers/agents/__tests__/client.steerWiring.spec.js
@@ -1,5 +1,6 @@
const AgentClient = require('../client');
const {
+ GenerationJobManager,
isSteeringSupported,
isSteerPreemptSupported,
isSteerTerminalContinuationSupported,
@@ -93,4 +94,47 @@ describe('AgentClient.buildSteerWiring — preempt capability gating', () => {
expect(wiring.hook).not.toBe(wiring.preemptHook);
expect(applySteerPart).not.toHaveBeenCalled();
});
+
+ it('durably corrects an applied steer after media encoding rejects its files', async () => {
+ const part = {
+ type: 'steer',
+ steer: 'keep the text',
+ steerId: 'steer-1',
+ files: [{ file_id: 'rejected-file' }],
+ };
+ const turnAttachments = [part.files[0]];
+ const telemetryAttachments = [part.files[0]];
+ const self = {
+ appliedSteerParts: new Map([['steer-1', { index: 2, part }]]),
+ admittedSteerAttachments: new Map([['steer-1', [part.files[0]]]]),
+ turnSharedAttachmentFiles: turnAttachments,
+ attachmentMemoryContext: { attachments: telemetryAttachments },
+ contentParts: [undefined, undefined, part],
+ responseMessageId: 'response-1',
+ conversationId: 'conversation-1',
+ jobCreatedAt: 1700000000000,
+ rollbackSteerAttachmentAdmission: AgentClient.prototype.rollbackSteerAttachmentAdmission,
+ };
+ const emitChunk = jest.spyOn(GenerationJobManager, 'emitChunk').mockResolvedValue();
+
+ await AgentClient.prototype.stripSteerAttachmentRefs.call(self, 'stream-1', {
+ steerId: 'steer-1',
+ });
+
+ expect(self.contentParts[2]).not.toHaveProperty('files');
+ expect(self.turnSharedAttachmentFiles).toBe(turnAttachments);
+ expect(self.turnSharedAttachmentFiles).toEqual([]);
+ expect(self.attachmentMemoryContext.attachments).toBe(telemetryAttachments);
+ expect(self.attachmentMemoryContext.attachments).toEqual([]);
+ expect(self.admittedSteerAttachments).toEqual(new Map());
+ expect(emitChunk).toHaveBeenCalledWith(
+ 'stream-1',
+ expect.objectContaining({
+ event: 'on_steer_applied',
+ data: expect.objectContaining({ index: 2, part: self.contentParts[2] }),
+ }),
+ { durable: true, expectedCreatedAt: 1700000000000 },
+ );
+ emitChunk.mockRestore();
+ });
});
diff --git a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
index a0891694cb..a264ea36df 100644
--- a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
+++ b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js
@@ -251,6 +251,7 @@ jest.mock('@librechat/data-schemas', () => ({
jest.mock('@librechat/api', () => ({
sendEvent: jest.fn(),
+ logAgentMemorySnapshot: jest.fn(),
isScheduleFireRequest: (...args) => mockIsScheduleFireRequest(...args),
exemptFromConcurrencyLimiter: (...args) => mockExemptFromConcurrencyLimiter(...args),
toPendingSteer: jest.fn((item) => item),
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js
index b4d29ec2d6..b4f9b0d017 100644
--- a/api/server/controllers/agents/client.js
+++ b/api/server/controllers/agents/client.js
@@ -115,7 +115,15 @@ const {
isSkillPrimeMessage,
collectFileIds,
processTextWithTokenLimit,
+ logAgentMemorySnapshot,
+ createAgentMemoryCallback,
+ assertAgentAttachmentLimits,
+ assertAgentAttachmentTopology,
+ isModelBoundAttachmentFile,
+ isAgentAttachmentLimitError,
+ isAttachmentObjectNotFoundError,
buildAgentScopedContext,
+ buildAgentScopedAttachmentMap,
buildAgentContextAttachmentsByAgentId,
buildSkillPrimeContentParts,
buildInitialToolSessions,
@@ -128,6 +136,7 @@ const {
decrementPendingRequest,
maybePrewarmCodeSandbox,
assertModelBoundContent,
+ filterFilesByEndpointRuntimeConfig,
createModelBoundChatModelCallback: createModelBoundContentCallback,
createInitialModelBoundAdmissionCallback,
hasModelBoundContentProtection,
@@ -167,6 +176,7 @@ const {
Permissions,
VisionModes,
ContentTypes,
+ FileSources,
ApprovalEvents,
EModelEndpoint,
PermissionTypes,
@@ -357,6 +367,175 @@ function getUserFacingRequestError(baseMessage, error, appConfig) {
}
class AgentClient extends BaseClient {
+ getModelBoundAttachmentsForEndpoint(attachments) {
+ return filterFilesByEndpointRuntimeConfig(this.options.req.config, {
+ files: (attachments ?? []).filter(isModelBoundAttachmentFile),
+ endpoint: this.options.agent?.endpoint ?? this.options.endpoint ?? EModelEndpoint.agents,
+ endpointType: this.options.endpointType,
+ skipTotalSizeLimit: true,
+ preserveTextSources: true,
+ });
+ }
+
+ getProcessableAttachmentsForEndpoint(attachments, modelBoundAttachments) {
+ const admittedModelAttachments =
+ modelBoundAttachments ?? this.getModelBoundAttachmentsForEndpoint(attachments);
+ const admittedObjects = new Set(admittedModelAttachments);
+ const admittedFileIds = collectFileIds(admittedModelAttachments);
+ return (attachments ?? []).filter(
+ (file) =>
+ !isModelBoundAttachmentFile(file) ||
+ admittedObjects.has(file) ||
+ (file?.file_id && admittedFileIds.has(file.file_id)),
+ );
+ }
+
+ async addDocuments(message, attachments) {
+ const memoryContext = {
+ req: this.options.req,
+ conversationId: this.conversationId,
+ messageId: message.messageId,
+ attachments,
+ };
+ logAgentMemorySnapshot('before_encode_documents', memoryContext);
+ try {
+ return await super.addDocuments(message, attachments);
+ } finally {
+ logAgentMemorySnapshot('after_encode_documents', memoryContext);
+ }
+ }
+
+ async processAttachments(message, attachments) {
+ const modelBoundAttachments = this.getModelBoundAttachmentsForEndpoint(attachments);
+ const processableAttachments = this.getProcessableAttachmentsForEndpoint(
+ attachments,
+ modelBoundAttachments,
+ );
+ assertAgentAttachmentLimits({
+ attachments: modelBoundAttachments,
+ req: this.options.req,
+ endpoint: this.options.agent?.endpoint ?? this.options.endpoint,
+ endpointType: this.options.endpointType,
+ });
+ const memoryContext = {
+ req: this.options.req,
+ conversationId: this.conversationId,
+ messageId: message.messageId,
+ attachments: modelBoundAttachments,
+ };
+ logAgentMemorySnapshot('before_process_attachments', memoryContext);
+ try {
+ return await super.processAttachments(message, processableAttachments);
+ } finally {
+ logAgentMemorySnapshot('after_process_attachments', memoryContext);
+ }
+ }
+
+ getFilteredScopedAttachmentMap(
+ sharedAttachmentIds,
+ attachmentsByAgentId = this.options.agentContextAttachmentsByAgentId,
+ agents = collectReachableAgents([this.options.agent, ...(this.agentConfigs?.values() ?? [])]),
+ ) {
+ const identifiedAgents = agents.filter((agent) => agent?.id);
+ const endpointsByAgentId = new Map(
+ identifiedAgents.map((agent) => [
+ agent.id,
+ {
+ endpoint: agent.endpoint,
+ endpointType: agent === this.options.agent ? this.options.endpointType : undefined,
+ },
+ ]),
+ );
+ return buildAgentScopedAttachmentMap({
+ agentIds: identifiedAgents.map((agent) => agent.id),
+ attachmentsByAgentId,
+ sharedRunAttachmentIds: sharedAttachmentIds,
+ req: this.options.req,
+ endpoint: this.options.agent?.endpoint ?? this.options.endpoint ?? EModelEndpoint.agents,
+ endpointType: this.options.endpointType,
+ endpointsByAgentId,
+ });
+ }
+
+ assertTurnAttachmentLimits(sharedAttachments, scopedAttachmentInjections) {
+ assertAgentAttachmentLimits({
+ attachments: [...sharedAttachments, ...scopedAttachmentInjections],
+ req: this.options.req,
+ endpoint: this.options.agent?.endpoint ?? this.options.endpoint,
+ endpointType: this.options.endpointType,
+ countRepeatedExtractedText: true,
+ enforceAttachmentCount: false,
+ useGlobalContextSizeLimit: true,
+ });
+ }
+
+ admitSteerAttachments(files, steerId) {
+ const modelBoundFiles = files.filter(isModelBoundAttachmentFile);
+ assertModelBoundContent({
+ filters: this.options.req?.config?.filters,
+ files: modelBoundFiles,
+ });
+ const sharedAttachments = [...(this.turnSharedAttachmentFiles ?? []), ...modelBoundFiles];
+ const scopedAttachmentsByAgentId = this.turnScopedAttachmentsByAgentId ?? new Map();
+ assertAgentAttachmentTopology({
+ sharedAttachments,
+ scopedAttachmentsByAgentId,
+ req: this.options.req,
+ endpoint: this.options.agent?.endpoint ?? this.options.endpoint,
+ endpointType: this.options.endpointType,
+ endpointsByAgentId: this.turnAttachmentEndpointsByAgentId,
+ });
+ this.assertTurnAttachmentLimits(
+ [...sharedAttachments, ...(this.turnAggregateOnlyAttachmentFiles ?? [])],
+ [...scopedAttachmentsByAgentId.values()].flat(),
+ );
+ this.turnSharedAttachmentFiles = sharedAttachments;
+ this.attachmentMemoryContext?.attachments?.push(...modelBoundFiles);
+ if (steerId && modelBoundFiles.length > 0) {
+ this.admittedSteerAttachments.set(steerId, modelBoundFiles);
+ }
+ }
+
+ async assertHistoricalAttachmentLimits(historicalAttachments) {
+ const currentAttachments = this.options.attachments ? await this.options.attachments : [];
+ const compatibleHistoricalAttachments =
+ this.getModelBoundAttachmentsForEndpoint(historicalAttachments);
+ const compatibleCurrentAttachments =
+ this.getModelBoundAttachmentsForEndpoint(currentAttachments);
+ const sharedAttachments = [...compatibleHistoricalAttachments, ...compatibleCurrentAttachments];
+ const sharedAttachmentIds = collectFileIds(sharedAttachments);
+ const agents = collectReachableAgents([
+ this.options.agent,
+ ...(this.agentConfigs?.values() ?? []),
+ ]);
+ const scopedAttachmentMap = this.getFilteredScopedAttachmentMap(
+ sharedAttachmentIds,
+ this.options.agentContextAttachmentsByAgentId,
+ agents,
+ );
+ const endpointsByAgentId = new Map(
+ agents
+ .filter((agent) => agent?.id)
+ .map((agent) => [
+ agent.id,
+ {
+ endpoint: agent.endpoint,
+ endpointType: agent === this.options.agent ? this.options.endpointType : undefined,
+ },
+ ]),
+ );
+ assertAgentAttachmentTopology({
+ sharedAttachments,
+ scopedAttachmentsByAgentId: scopedAttachmentMap,
+ req: this.options.req,
+ endpoint: this.options.agent?.endpoint ?? this.options.endpoint,
+ endpointType: this.options.endpointType,
+ endpointsByAgentId,
+ });
+ this.assertTurnAttachmentLimits(sharedAttachments, [...scopedAttachmentMap.values()].flat());
+ return compatibleHistoricalAttachments;
+ }
+
/** Mirrors the SDK's `MultiAgentGraph.analyzeGraph`: every loaded agent
* without an incoming edge starts in the first graph wave, falling back to
* the first agent for a cycle. */
@@ -561,6 +740,8 @@ class AgentClient extends BaseClient {
* SDK-emitted indices that arrive after an injection land past it.
* @type {import('@librechat/api').SteerOffsetState} */
this.steerOffsetState = { offset: 0 };
+ this.appliedSteerParts = new Map();
+ this.admittedSteerAttachments = new Map();
/** @type {(messages: BaseMessage[], inspectionMessages?: BaseMessage[]) => Promise<void>} */
this.processMemory;
}
@@ -674,6 +855,7 @@ class AgentClient extends BaseClient {
deliveredSteer: item,
},
);
+ this.appliedSteerParts.set(item.steerId, { index, part });
/** Only a COMMITTED steer is a hard semantic boundary. If its durable
* append failed, the drain restores the queue item and the current
* phase evidence must remain intact for the eventual retry. */
@@ -686,10 +868,62 @@ class AgentClient extends BaseClient {
this.contentParts.splice(index, 1);
this.steerOffsetState.offset -= 1;
}
+ this.appliedSteerParts.delete(item.steerId);
throw error;
}
}
+ async stripSteerAttachmentRefs(streamId, item) {
+ this.rollbackSteerAttachmentAdmission(item.steerId);
+ const applied = this.appliedSteerParts.get(item.steerId);
+ if (!applied?.part?.files?.length) {
+ return;
+ }
+ const part = { ...applied.part };
+ delete part.files;
+ this.contentParts[applied.index] = part;
+ this.appliedSteerParts.set(item.steerId, { index: applied.index, part });
+ await GenerationJobManager.emitChunk(
+ streamId,
+ {
+ event: SteerEvents.ON_STEER_APPLIED,
+ data: {
+ steerId: item.steerId,
+ ...(item.clientSteerId && { clientSteerId: item.clientSteerId }),
+ index: applied.index,
+ part,
+ responseMessageId: this.responseMessageId,
+ conversationId: this.conversationId,
+ },
+ },
+ {
+ durable: true,
+ expectedCreatedAt: this.jobCreatedAt,
+ },
+ );
+ }
+
+ rollbackSteerAttachmentAdmission(steerId) {
+ const admitted = this.admittedSteerAttachments.get(steerId);
+ this.admittedSteerAttachments.delete(steerId);
+ if (!admitted?.length) {
+ return;
+ }
+ const removeOccurrences = (files) => {
+ if (!Array.isArray(files)) {
+ return;
+ }
+ for (let index = admitted.length - 1; index >= 0; index--) {
+ const occurrence = files.lastIndexOf(admitted[index]);
+ if (occurrence >= 0) {
+ files.splice(occurrence, 1);
+ }
+ }
+ };
+ removeOccurrences(this.turnSharedAttachmentFiles);
+ removeOccurrences(this.attachmentMemoryContext?.attachments);
+ }
+
/**
* The `steering` fragment for `createRun`: the run-scoped PostToolBatch
* drain hook — plus the capability-gated PreemptBoundary and terminal Stop
@@ -708,18 +942,18 @@ class AgentClient extends BaseClient {
streamId,
jobCreatedAt: this.jobCreatedAt,
applySteer: (item) => this.applySteerPart(streamId, item),
- buildMedia: (item) =>
- buildSteerMedia({
+ onMediaError: (item) => this.stripSteerAttachmentRefs(streamId, item),
+ buildMedia: async (item) => {
+ const media = await buildSteerMedia({
client: this,
user: this.options.req?.user,
item,
getFiles: db.getFiles,
- assertFilesAllowed: (files) =>
- assertModelBoundContent({
- filters: this.options.req?.config?.filters,
- files,
- }),
- }),
+ assertFilesAllowed: (files) => this.admitSteerAttachments(files, item.steerId),
+ });
+ this.admittedSteerAttachments.delete(item.steerId);
+ return media;
+ },
};
return {
hook: createSteerDrainHook(drainOptions),
@@ -1736,9 +1970,12 @@ class AgentClient extends BaseClient {
}
shouldDeferUserMessagePersistence() {
- return hasModelBoundContentProtection(
- this.options.req?.config?.filters,
- this.options.req?.config?.messageFilter?.pii,
+ return (
+ (Array.isArray(this.modelBoundCurrentFiles) && this.modelBoundCurrentFiles.length > 0) ||
+ hasModelBoundContentProtection(
+ this.options.req?.config?.filters,
+ this.options.req?.config?.messageFilter?.pii,
+ )
);
}
@@ -2058,6 +2295,15 @@ class AgentClient extends BaseClient {
}
}
const allAgents = [...agentsById].map(([agentId, agent]) => ({ agent, agentId }));
+ const endpointsByAgentId = new Map(
+ allAgents.map(({ agent, agentId }) => [
+ agentId,
+ {
+ endpoint: agent.endpoint,
+ endpointType: agent === this.options.agent ? this.options.endpointType : undefined,
+ },
+ ]),
+ );
const dynamicToolContexts = getDynamicToolContexts(allAgents.map(({ agent }) => agent));
for (const context of dynamicToolContexts) {
modelBoundFileContexts.add(context);
@@ -2093,7 +2339,54 @@ class AgentClient extends BaseClient {
agents: allAgents.map(({ agent }) => agent),
files: [...modelBoundFileContexts],
});
- const sharedRunAttachmentIds = new Set();
+ const requestAttachmentsSource = this.options.attachments;
+ const requestAttachments = requestAttachmentsSource ? await requestAttachmentsSource : [];
+ const modelBoundRequestAttachments =
+ this.getModelBoundAttachmentsForEndpoint(requestAttachments);
+ const retainedHistoricalFileContexts =
+ this.options.resendFiles === false
+ ? orderedMessages
+ .filter((message) => typeof message?.fileContext === 'string' && message.fileContext)
+ .map((message, index) => ({
+ file_id: `retained-file-context:${message.messageId ?? message.id ?? index}`,
+ source: FileSources.text,
+ type: 'text/plain',
+ text: message.fileContext,
+ bytes: Buffer.byteLength(message.fileContext, 'utf8'),
+ }))
+ : [];
+ const sharedAttachmentFiles = [
+ ...Object.values(this.message_file_map ?? {}).flat(),
+ ...(this.modelBoundHistoricalSteerFiles ?? []),
+ ...modelBoundRequestAttachments,
+ ];
+ const sharedRunAttachmentIds = collectFileIds(sharedAttachmentFiles);
+ const scopedAttachmentMap = buildAgentScopedAttachmentMap({
+ agentIds: allAgents.map(({ agentId }) => agentId),
+ attachmentsByAgentId: this.options.agentContextAttachmentsByAgentId,
+ sharedRunAttachmentIds,
+ req: this.options.req,
+ endpoint: this.options.agent?.endpoint ?? this.options.endpoint ?? EModelEndpoint.agents,
+ endpointType: this.options.endpointType,
+ endpointsByAgentId,
+ });
+ this.turnSharedAttachmentFiles = sharedAttachmentFiles;
+ this.turnAggregateOnlyAttachmentFiles = retainedHistoricalFileContexts;
+ this.turnScopedAttachmentsByAgentId = scopedAttachmentMap;
+ this.turnAttachmentEndpointsByAgentId = endpointsByAgentId;
+ assertAgentAttachmentTopology({
+ sharedAttachments: sharedAttachmentFiles,
+ scopedAttachmentsByAgentId: scopedAttachmentMap,
+ req: this.options.req,
+ endpoint: this.options.agent?.endpoint ?? this.options.endpoint,
+ endpointType: this.options.endpointType,
+ endpointsByAgentId,
+ });
+ const attachmentContextInjections = [...scopedAttachmentMap.values()].flat();
+ this.assertTurnAttachmentLimits(
+ [...sharedAttachmentFiles, ...retainedHistoricalFileContexts],
+ attachmentContextInjections,
+ );
/** @type {ReturnType<typeof buildAgentScopedContext>} */
let agentScopedContextPromise;
const startAgentScopedContext = () => {
@@ -2101,31 +2394,34 @@ class AgentClient extends BaseClient {
agentIds: allAgents.map(({ agentId }) => agentId),
attachmentsByAgentId: this.options.agentContextAttachmentsByAgentId,
sharedRunAttachmentIds,
+ sharedAttachments: sharedAttachmentFiles,
req: this.options.req,
+ endpoint: this.options.agent?.endpoint ?? this.options.endpoint ?? EModelEndpoint.agents,
+ endpointType: this.options.endpointType,
+ endpointsByAgentId,
tokenCountFn: (text) => countTokens(text),
});
void contextPromise.catch(() => {});
return contextPromise;
};
- if (this.options.attachments) {
- const attachments = await this.options.attachments;
+ if (requestAttachmentsSource) {
+ const attachments = this.getProcessableAttachmentsForEndpoint(
+ requestAttachments,
+ modelBoundRequestAttachments,
+ );
const latestMessage = orderedMessages[orderedMessages.length - 1];
- this.modelBoundCurrentFiles = [...attachments];
+ this.modelBoundCurrentFiles = [...modelBoundRequestAttachments];
assertModelBoundContent({
filters: this.options.req.config?.filters,
- files: attachments,
+ files: modelBoundRequestAttachments,
});
- for (const attachment of attachments) {
+ for (const attachment of modelBoundRequestAttachments) {
if (attachment) {
modelBoundFileContexts.add(attachment);
}
}
- for (const fileId of collectFileIds(attachments)) {
- sharedRunAttachmentIds.add(fileId);
- }
-
/** Agent-scoped extraction only depends on the shared attachment IDs. */
agentScopedContextPromise = startAgentScopedContext();
@@ -2138,7 +2434,7 @@ class AgentClient extends BaseClient {
}
const [, files] = await Promise.all([
- this.addFileContextToMessage(latestMessage, attachments),
+ this.addFileContextToMessage(latestMessage, modelBoundRequestAttachments),
this.processAttachments(latestMessage, attachments),
]);
@@ -2147,6 +2443,20 @@ class AgentClient extends BaseClient {
agentScopedContextPromise = startAgentScopedContext();
}
+ const attachmentTelemetryFiles = [
+ ...sharedAttachmentFiles,
+ ...retainedHistoricalFileContexts,
+ ...attachmentContextInjections,
+ ];
+ this.attachmentMemoryContext = {
+ req: this.options.req,
+ conversationId: this.conversationId,
+ messageId: orderedMessages[orderedMessages.length - 1]?.messageId,
+ attachments: attachmentTelemetryFiles,
+ countRepeatedExtractedText: true,
+ };
+ logAgentMemorySnapshot('before_context_assembly', this.attachmentMemoryContext);
+
/** Note: Bedrock uses legacy RAG API handling */
if (this.message_file_map && !isAgentsEndpoint(this.options.endpoint)) {
this.contextHandlers = createContextHandlers(
@@ -2386,7 +2696,7 @@ class AgentClient extends BaseClient {
targets: steerStampTargets,
// addPreviousAttachments already fetched steer-part refs in its single
// per-turn historical-files query — no second round trip.
- docsById: this.authorizedHistoricalFiles,
+ docsById: this.authorizedHistoricalReplayFiles ?? this.authorizedHistoricalFiles,
getFiles: db.getFiles,
resendFiles: resendSteerFiles,
});
@@ -2721,11 +3031,41 @@ class AgentClient extends BaseClient {
(agent) => !runtimeAgentPreparations.has(agent),
);
if (unpreparedAgents.length > 0) {
+ const liveSharedAttachmentFiles =
+ this.turnSharedAttachmentFiles ?? sharedAttachmentFiles;
+ const liveSharedAttachmentIds = collectFileIds(liveSharedAttachmentFiles);
+ const lateAttachmentsByAgentId =
+ buildAgentContextAttachmentsByAgentId(unpreparedAgents);
+ const lateScopedAttachmentMap = this.getFilteredScopedAttachmentMap(
+ liveSharedAttachmentIds,
+ lateAttachmentsByAgentId,
+ unpreparedAgents,
+ );
+ const lateAttachmentInjections = [...lateScopedAttachmentMap.values()].flat();
+ attachmentContextInjections.push(...lateAttachmentInjections);
+ attachmentTelemetryFiles.push(...lateAttachmentInjections);
+ this.assertTurnAttachmentLimits(
+ [...liveSharedAttachmentFiles, ...(this.turnAggregateOnlyAttachmentFiles ?? [])],
+ attachmentContextInjections,
+ );
+ const lateEndpointsByAgentId = new Map(
+ unpreparedAgents.map((agent) => [agent.id, { endpoint: agent.endpoint }]),
+ );
+ for (const [agentId, attachments] of lateScopedAttachmentMap) {
+ this.turnScopedAttachmentsByAgentId.set(agentId, attachments);
+ }
+ for (const [agentId, agentEndpoint] of lateEndpointsByAgentId) {
+ this.turnAttachmentEndpointsByAgentId.set(agentId, agentEndpoint);
+ }
const pending = buildAgentScopedContext({
agentIds: unpreparedAgents.map((agent) => agent.id),
- attachmentsByAgentId: buildAgentContextAttachmentsByAgentId(unpreparedAgents),
- sharedRunAttachmentIds,
+ attachmentsByAgentId: lateAttachmentsByAgentId,
+ sharedRunAttachmentIds: liveSharedAttachmentIds,
+ sharedAttachments: liveSharedAttachmentFiles,
req: this.options.req,
+ endpoint: this.options.agent?.endpoint ?? this.options.endpoint,
+ endpointType: this.options.endpointType,
+ endpointsByAgentId: lateEndpointsByAgentId,
tokenCountFn: (text) => countTokens(text),
}).then((lateScopedContext) =>
Promise.all(
@@ -2751,6 +3091,7 @@ class AgentClient extends BaseClient {
};
wrapLazyResolvers([this.options.agent, ...(this.agentConfigs?.values() ?? [])]);
+ logAgentMemorySnapshot('after_context_assembly', this.attachmentMemoryContext);
return result;
}
@@ -4384,7 +4725,10 @@ class AgentClient extends BaseClient {
messages,
discoveredToolNames:
this.eventActorContinuation === 'warm' ? this.eventActorDiscoveredToolNames : undefined,
- modelCallbacks: [modelBoundCallback],
+ modelCallbacks: [
+ modelBoundCallback,
+ createAgentMemoryCallback(this.attachmentMemoryContext ?? {}),
+ ],
// This controller implements the full HITL pause/resume lifecycle (handleRunInterrupt
// persists the pending action; the /resume route rebuilds + continues the run), so it
// opts into the tool-approval wiring. Non-resumable callers (OpenAI-compat, Responses)
@@ -4588,7 +4932,22 @@ class AgentClient extends BaseClient {
);
throw err;
}
- if (abortController.signal.aborted) {
+ if (isAgentAttachmentLimitError(err) || isAttachmentObjectNotFoundError(err)) {
+ logger.warn(
+ '[api/server/controllers/agents/client.js #sendCompletion] Attachment rejected',
+ {
+ conversationId: this.conversationId,
+ ...getSafeErrorMetadata(err),
+ },
+ );
+ BaseClient.prototype.getModelBoundUserMessagePersistence.call(this)?.cancel();
+ this.options.attachments = [];
+ this.modelBoundCurrentFiles = [];
+ this.contentParts.push({
+ type: ContentTypes.ERROR,
+ [ContentTypes.ERROR]: err.message,
+ });
+ } else if (abortController.signal.aborted) {
logger.debug(
'[api/server/controllers/agents/client.js #sendCompletion] Operation aborted by user',
{ conversationId: this.conversationId, ...getSafeErrorMetadata(err) },
@@ -4815,6 +5174,7 @@ class AgentClient extends BaseClient {
const liveFiles = Array.isArray(this.options.attachments)
? [...this.options.attachments]
: [];
+ const requestFiles = [...liveFiles];
const modelBoundAgentFiles = [];
const contextAttachmentLists =
this.options.agentContextAttachmentsByAgentId instanceof Map
@@ -4865,7 +5225,199 @@ class AgentClient extends BaseClient {
...(Array.isArray(this.modelBoundCurrentFiles) ? this.modelBoundCurrentFiles : []),
...resumeContentProjection.resolvedFiles,
];
+ const checkpointFileIds = collectFileIds(resumeContentProjection.checkpointFiles);
+ const resumeSharedFiles = [
+ ...resumeContentProjection.checkpointFiles.filter(isModelBoundAttachmentFile),
+ ...AgentClient.prototype.getModelBoundAttachmentsForEndpoint
+ .call(this, requestFiles)
+ .filter((file) => !file?.file_id || !checkpointFileIds.has(file.file_id)),
+ ];
+ const resumeSharedFileIds = collectFileIds(resumeSharedFiles);
+ const resumeEndpointsByAgentId = new Map(
+ agents
+ .filter((agent) => agent?.id)
+ .map((agent) => [
+ agent.id,
+ {
+ endpoint: agent.endpoint,
+ endpointType: agent === this.options.agent ? this.options.endpointType : undefined,
+ },
+ ]),
+ );
+ const resumeMcpManager = getMCPManager();
+ const [resumeScopedContext, resumeConfigServers] = await Promise.all([
+ buildAgentScopedContext({
+ agentIds: agents.map((agent) => agent?.id).filter(Boolean),
+ attachmentsByAgentId: this.options.agentContextAttachmentsByAgentId,
+ sharedRunAttachmentIds: resumeSharedFileIds,
+ sharedAttachments: resumeSharedFiles,
+ req: this.options.req,
+ endpoint: this.options.agent?.endpoint ?? this.options.endpoint ?? EModelEndpoint.agents,
+ endpointType: this.options.endpointType,
+ endpointsByAgentId: resumeEndpointsByAgentId,
+ tokenCountFn: (text) => countTokens(text),
+ }),
+ resolveConfigServers(this.options.req),
+ ]);
+ const resumeScopedAttachmentMap = buildAgentScopedAttachmentMap({
+ agentIds: agents.map((agent) => agent?.id).filter(Boolean),
+ attachmentsByAgentId: this.options.agentContextAttachmentsByAgentId,
+ sharedRunAttachmentIds: resumeSharedFileIds,
+ req: this.options.req,
+ endpoint: this.options.agent?.endpoint ?? this.options.endpoint ?? EModelEndpoint.agents,
+ endpointType: this.options.endpointType,
+ endpointsByAgentId: resumeEndpointsByAgentId,
+ });
+ this.turnSharedAttachmentFiles = resumeSharedFiles;
+ this.turnAggregateOnlyAttachmentFiles = [];
+ this.turnScopedAttachmentsByAgentId = resumeScopedAttachmentMap;
+ this.turnAttachmentEndpointsByAgentId = resumeEndpointsByAgentId;
+ const resumeScopedAttachments = [...resumeScopedAttachmentMap.values()].flat();
+ AgentClient.prototype.assertTurnAttachmentLimits.call(
+ this,
+ resumeSharedFiles,
+ resumeScopedAttachments,
+ );
+ const resumeAttachmentTelemetryFiles = [...resumeSharedFiles, ...resumeScopedAttachments];
+ this.attachmentMemoryContext = {
+ req: this.options.req,
+ conversationId: this.conversationId,
+ messageId: this.responseMessageId,
+ attachments: resumeAttachmentTelemetryFiles,
+ countRepeatedExtractedText: true,
+ };
+ await Promise.all(
+ agents
+ .filter((agent) => agent?.id)
+ .map(async (agent) => {
+ agent.instructions = agent.instructions?.trim() || undefined;
+ agent.additional_instructions = agent.additional_instructions?.trim() || undefined;
+ const scopedContext = resumeScopedContext.get(agent.id);
+ await applyContextToAgent({
+ agent,
+ agentId: agent.id,
+ logger,
+ mcpManager: resumeMcpManager,
+ configServers: resumeConfigServers,
+ sharedRunContext: scopedContext ?? '',
+ ephemeralAgent:
+ agent === this.options.agent ? this.options.req.body.ephemeralAgent : undefined,
+ });
+ assertModelBoundContent({
+ filters: this.options.req.config?.filters,
+ legacyPii: this.options.req.config?.messageFilter?.pii,
+ agents: [agent],
+ files: scopedContext ? [scopedContext] : [],
+ });
+ }),
+ );
+ const wrappedResumeLazyDescriptors = new WeakSet();
+ const validatedResumeAgents = new WeakSet(agents.filter((agent) => agent != null));
+ const wrapResumeLazyAttachmentValidation = (configs) => {
+ const pending = [...configs];
+ const visitedConfigs = new WeakSet();
+ for (let index = 0; index < pending.length; index++) {
+ const config = pending[index];
+ if (!config || visitedConfigs.has(config)) {
+ continue;
+ }
+ visitedConfigs.add(config);
+ pending.push(...(config.subagentAgentConfigs ?? []));
+ for (const graph of config.subagentGraphConfigs ?? []) {
+ pending.push(...graph.memberConfigs);
+ }
+ for (const descriptor of config.lazySubagentConfigs ?? []) {
+ pending.push(descriptor);
+ if (
+ wrappedResumeLazyDescriptors.has(descriptor) ||
+ typeof descriptor?.resolve !== 'function'
+ ) {
+ continue;
+ }
+ wrappedResumeLazyDescriptors.add(descriptor);
+ const resolve = descriptor.resolve;
+ descriptor.resolve = async (context) => {
+ const resolved = await resolve(context);
+ const resolvedAgents = collectReachableAgents([resolved]);
+ const unvalidatedAgents = resolvedAgents.filter(
+ (agent) => agent != null && !validatedResumeAgents.has(agent),
+ );
+ if (unvalidatedAgents.length === 0) {
+ wrapResumeLazyAttachmentValidation(resolvedAgents);
+ return resolved;
+ }
+ const liveResumeSharedFiles = this.turnSharedAttachmentFiles ?? resumeSharedFiles;
+ const liveResumeSharedFileIds = collectFileIds(liveResumeSharedFiles);
+ const lateAttachmentsByAgentId =
+ buildAgentContextAttachmentsByAgentId(unvalidatedAgents);
+ const lateEndpointsByAgentId = new Map(
+ unvalidatedAgents
+ .filter((agent) => agent?.id)
+ .map((agent) => [agent.id, { endpoint: agent.endpoint }]),
+ );
+ const lateScopedAttachmentMap = buildAgentScopedAttachmentMap({
+ agentIds: unvalidatedAgents.map((agent) => agent?.id).filter(Boolean),
+ attachmentsByAgentId: lateAttachmentsByAgentId,
+ sharedRunAttachmentIds: liveResumeSharedFileIds,
+ req: this.options.req,
+ endpoint: this.options.agent?.endpoint ?? this.options.endpoint,
+ endpointType: this.options.endpointType,
+ endpointsByAgentId: lateEndpointsByAgentId,
+ });
+ for (const [agentId, attachments] of lateScopedAttachmentMap) {
+ this.turnScopedAttachmentsByAgentId.set(agentId, attachments);
+ }
+ for (const [agentId, agentEndpoint] of lateEndpointsByAgentId) {
+ this.turnAttachmentEndpointsByAgentId.set(agentId, agentEndpoint);
+ }
+ const lateScopedContext = await buildAgentScopedContext({
+ agentIds: unvalidatedAgents.map((agent) => agent?.id).filter(Boolean),
+ attachmentsByAgentId: lateAttachmentsByAgentId,
+ sharedRunAttachmentIds: liveResumeSharedFileIds,
+ sharedAttachments: liveResumeSharedFiles,
+ req: this.options.req,
+ endpoint: this.options.agent?.endpoint ?? this.options.endpoint,
+ endpointType: this.options.endpointType,
+ endpointsByAgentId: lateEndpointsByAgentId,
+ tokenCountFn: (text) => countTokens(text),
+ });
+ const lateScopedAttachments = [...lateScopedAttachmentMap.values()].flat();
+ resumeScopedAttachments.push(...lateScopedAttachments);
+ resumeAttachmentTelemetryFiles.push(...lateScopedAttachments);
+ AgentClient.prototype.assertTurnAttachmentLimits.call(
+ this,
+ liveResumeSharedFiles,
+ resumeScopedAttachments,
+ );
+ for (const agent of unvalidatedAgents) {
+ agent.instructions = agent.instructions?.trim() || undefined;
+ agent.additional_instructions = agent.additional_instructions?.trim() || undefined;
+ const scopedContext = lateScopedContext.get(agent.id);
+ await applyContextToAgent({
+ agent,
+ agentId: agent.id,
+ logger,
+ mcpManager: resumeMcpManager,
+ configServers: resumeConfigServers,
+ sharedRunContext: scopedContext ?? '',
+ });
+ assertModelBoundContent({
+ filters: this.options.req.config?.filters,
+ legacyPii: this.options.req.config?.messageFilter?.pii,
+ agents: [agent],
+ files: scopedContext ? [scopedContext] : [],
+ });
+ validatedResumeAgents.add(agent);
+ }
+ wrapResumeLazyAttachmentValidation(resolvedAgents);
+ return resolved;
+ };
+ }
+ }
+ };
+ wrapResumeLazyAttachmentValidation(agents);
const modelBoundCallback = AgentClient.prototype.createModelBoundChatModelCallback.call(this);
+ const attachmentMemoryCallback = createAgentMemoryCallback(this.attachmentMemoryContext);
// Re-prime skill files invoked in the pre-pause segment (mirrors the normal path's
// `primeInvokedSkills(payload)`), so an approved code/file-backed tool keeps the
@@ -4919,7 +5471,7 @@ class AgentClient extends BaseClient {
run = await createRun({
agents,
conversationId: this.conversationId,
- modelCallbacks: [modelBoundCallback],
+ modelCallbacks: [modelBoundCallback, attachmentMemoryCallback],
// State (messages, tool calls) is rehydrated from the checkpoint by
// run.resume; createRun only needs the agents to rebuild the graph.
messages: [],
@@ -5039,6 +5591,16 @@ class AgentClient extends BaseClient {
this.applyHideSequentialOutputsFilter();
this.rebaseActivityPhaseBounds(contentBeforeReshape);
} catch (err) {
+ if (isAgentAttachmentLimitError(err) || isAttachmentObjectNotFoundError(err)) {
+ logger.warn(
+ '[api/server/controllers/agents/client.js #resumeCompletion] Attachment rejected',
+ {
+ conversationId: this.conversationId,
+ ...getSafeErrorMetadata(err),
+ },
+ );
+ throw err;
+ }
if (isContentFilterError(err)) {
logger.warn(
'[api/server/controllers/agents/client.js #resumeCompletion] Blocked by content policy',
diff --git a/api/server/controllers/agents/client.test.js b/api/server/controllers/agents/client.test.js
index 1b351ad011..c7c603e960 100644
--- a/api/server/controllers/agents/client.test.js
+++ b/api/server/controllers/agents/client.test.js
@@ -1293,7 +1293,7 @@ describe('AgentClient - interrupt discovery persistence', () => {
const client = new AgentClient({
req: {
user: { id: 'user-123' },
- body: { endpoint: EModelEndpoint.agents, agent_id: 'agent-123' },
+ body: { endpoint: EModelEndpoint.agents, agent_id: 'agent-123', isTemporary: true },
config: { endpoints: { [EModelEndpoint.agents]: {} } },
_resumableStreamId: streamId,
},
@@ -1446,7 +1446,7 @@ describe('AgentClient - interrupt discovery persistence', () => {
const client = new AgentClient({
req: {
user: { id: 'user-123' },
- body: { endpoint: EModelEndpoint.agents, agent_id: 'agent-123' },
+ body: { endpoint: EModelEndpoint.agents, agent_id: 'agent-123', isTemporary: true },
config: { endpoints: { [EModelEndpoint.agents]: {} } },
_resumableStreamId: streamId,
},
@@ -2278,12 +2278,15 @@ describe('AgentClient - startup telemetry', () => {
expect(mockCreateRun.mock.calls[0][0]).toEqual(
expect.objectContaining({
tenantId: 'request-tenant',
- modelCallbacks: [
+ modelCallbacks: expect.arrayContaining([
expect.objectContaining({
name: 'librechat-model-bound-content-filter',
raiseError: true,
}),
- ],
+ expect.objectContaining({
+ name: 'librechat-agent-attachment-memory',
+ }),
+ ]),
}),
);
expect(mockDeleteAgentCheckpoint).toHaveBeenCalledWith(
@@ -2716,6 +2719,138 @@ describe('AgentClient - startup telemetry', () => {
);
});
+ it('cancels current attachment persistence after combined admission rejects the run', async () => {
+ jest.clearAllMocks();
+ let attachmentLimitError;
+ try {
+ require('@librechat/api').assertAgentAttachmentLimits({
+ attachments: [{ file_id: 'too-large', bytes: 2_000_000 }],
+ fileConfig: { fileContextSizeLimit: 1 },
+ });
+ } catch (error) {
+ attachmentLimitError = error;
+ }
+ expect(attachmentLimitError).toEqual(
+ expect.objectContaining({ code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED' }),
+ );
+ expect(require('@librechat/api').isAgentAttachmentLimitError(attachmentLimitError)).toBe(true);
+ mockCreateRun.mockResolvedValue({
+ Graph: null,
+ processStream: jest.fn().mockRejectedValue(attachmentLimitError),
+ getCalibrationRatio: jest.fn(() => 0),
+ });
+ mockIsHITLEnabled.mockReturnValue(false);
+ const currentFile = { file_id: 'rejected-current', bytes: 600_000 };
+ const cancel = jest.fn();
+ const client = new AgentClient({
+ req: {
+ user: { id: 'user-123' },
+ body: { files: [{ file_id: currentFile.file_id }] },
+ config: { endpoints: { [EModelEndpoint.agents]: {} } },
+ _resumableStreamId: 'conversation-attachment-limit',
+ },
+ res: {},
+ agent: {
+ id: 'agent-123',
+ endpoint: EModelEndpoint.openAI,
+ provider: EModelEndpoint.openAI,
+ model_parameters: { model: 'gpt-4' },
+ hide_sequential_outputs: false,
+ },
+ attachments: [currentFile],
+ endpointTokenConfig: {},
+ eventHandlers: {},
+ contentParts: [],
+ collectedUsage: [],
+ artifactPromises: [],
+ });
+ client.conversationId = 'conversation-attachment-limit';
+ client.responseMessageId = 'response-attachment-limit';
+ client.parentMessageId = 'parent-attachment-limit';
+ client.modelBoundCurrentFiles = [currentFile];
+ client.modelBoundUserMessagePersistence = {
+ cancel,
+ isPending: jest.fn(() => true),
+ start: jest.fn(),
+ };
+ client.recordCollectedUsage = jest.fn().mockResolvedValue();
+
+ await client.chatCompletion({ payload: [] });
+
+ expect(cancel).toHaveBeenCalledTimes(1);
+ expect(client.options.attachments).toEqual([]);
+ expect(client.modelBoundCurrentFiles).toEqual([]);
+ expect(client.contentParts).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ type: ContentTypes.ERROR,
+ [ContentTypes.ERROR]: expect.stringContaining('total attachment size'),
+ }),
+ ]),
+ );
+ });
+
+ it('cancels current attachment persistence when its storage object is unavailable', async () => {
+ jest.clearAllMocks();
+ const attachmentError = new (require('@librechat/api').AttachmentObjectNotFoundError)(
+ 'missing-current',
+ );
+ mockCreateRun.mockResolvedValue({
+ Graph: null,
+ processStream: jest.fn().mockRejectedValue(attachmentError),
+ getCalibrationRatio: jest.fn(() => 0),
+ });
+ mockIsHITLEnabled.mockReturnValue(false);
+ const currentFile = { file_id: 'missing-current', bytes: 600_000 };
+ const cancel = jest.fn();
+ const client = new AgentClient({
+ req: {
+ user: { id: 'user-123' },
+ body: { files: [{ file_id: currentFile.file_id }] },
+ config: { endpoints: { [EModelEndpoint.agents]: {} } },
+ _resumableStreamId: 'conversation-missing-attachment',
+ },
+ res: {},
+ agent: {
+ id: 'agent-123',
+ endpoint: EModelEndpoint.openAI,
+ provider: EModelEndpoint.openAI,
+ model_parameters: { model: 'gpt-4' },
+ hide_sequential_outputs: false,
+ },
+ attachments: [currentFile],
+ endpointTokenConfig: {},
+ eventHandlers: {},
+ contentParts: [],
+ collectedUsage: [],
+ artifactPromises: [],
+ });
+ client.conversationId = 'conversation-missing-attachment';
+ client.responseMessageId = 'response-missing-attachment';
+ client.parentMessageId = 'parent-missing-attachment';
+ client.modelBoundCurrentFiles = [currentFile];
+ client.modelBoundUserMessagePersistence = {
+ cancel,
+ isPending: jest.fn(() => true),
+ start: jest.fn(),
+ };
+ client.recordCollectedUsage = jest.fn().mockResolvedValue();
+
+ await client.chatCompletion({ payload: [] });
+
+ expect(cancel).toHaveBeenCalledTimes(1);
+ expect(client.options.attachments).toEqual([]);
+ expect(client.modelBoundCurrentFiles).toEqual([]);
+ expect(client.contentParts).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ type: ContentTypes.ERROR,
+ [ContentTypes.ERROR]: expect.stringContaining('no longer available'),
+ }),
+ ]),
+ );
+ });
+
it('evolves warm compaction guidance while injecting only the new event message', async () => {
jest.clearAllMocks();
const history = { _getType: () => 'human', content: 'old turn' };
@@ -4433,7 +4568,9 @@ describe('AgentClient - titleConvo', () => {
file_id: 'request-file',
filename: 'request.txt',
source: 'text',
+ text: 'Request file contents',
type: 'text/plain',
+ bytes: 0,
};
client.options.attachments = requestAttachments.promise;
@@ -5261,157 +5398,549 @@ describe('AgentClient - titleConvo', () => {
).resolves.toEqual(expect.objectContaining({ prompt: expect.any(Array) }));
});
- it('filters historical attachment content only when its source survives pruning', async () => {
- const privateText = 'PRIVATE-HISTORICAL-CONTENT';
- mockReq.config.filters = {
- files: {
- pii: {
- fields: ['extracted_text'],
- starterPatterns: [],
- customPatterns: [{ id: 'private', label: 'private value', regex: privateText }],
- },
- },
- };
- client.options.resendFiles = true;
- require('~/models').getFiles.mockResolvedValue([
- makeTextFile('historical-file', 'history.txt', privateText),
- ]);
- client.addFileContextToMessage = jest.fn();
- client.processAttachments = jest.fn();
-
- const hydratedMessages = await client.addPreviousAttachments([
- {
- messageId: 'msg-1',
- parentMessageId: null,
- isCreatedByUser: true,
- files: [{ file_id: 'historical-file' }],
- },
- ]);
- client.setModelBoundStoredMessages([
- ...hydratedMessages,
- {
- messageId: 'safe-message',
- role: 'user',
- text: 'Safe retained turn',
- isCreatedByUser: true,
- },
- ]);
- const callback = client.createModelBoundChatModelCallback();
+ it('enforces extracted-text limits on retained history when file replay is disabled', async () => {
+ client.options.resendFiles = false;
+ mockReq.config.fileConfig = { fileContextCharLimit: 10 };
- expect(() =>
- callback.handleChatModelStart(undefined, [
+ await expect(
+ client.buildMessages(
[
{
- role: 'human',
- content: 'Safe retained turn',
- additional_kwargs: { sourceMessageId: 'safe-message' },
+ messageId: 'historical-context',
+ parentMessageId: null,
+ sender: 'User',
+ text: 'Inspect the retained context.',
+ isCreatedByUser: true,
+ fileContext: 'this retained context is over the configured limit',
},
- ],
- ]),
- ).not.toThrow();
- expect(() =>
- callback.handleChatModelStart(undefined, [
- [
{
- role: 'human',
- content: 'Use the historical file.',
- additional_kwargs: { sourceMessageId: 'msg-1' },
+ messageId: 'msg-1',
+ parentMessageId: 'historical-context',
+ sender: 'User',
+ text: 'Continue.',
+ isCreatedByUser: true,
},
],
- ]),
- ).toThrow(expect.objectContaining({ code: 'content_filter_block' }));
-
- expect(client.addFileContextToMessage).toHaveBeenCalled();
- expect(client.processAttachments).toHaveBeenCalled();
+ 'msg-1',
+ {},
+ ),
+ ).rejects.toMatchObject({
+ code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED',
+ limitType: 'extracted_text',
+ });
});
- it('does not run historical file contexts through the pre-pruning build preflight', async () => {
- const privateText = 'PRIVATE-PRUNED-HISTORICAL-FILE';
- mockReq.config.filters = {
- files: {
- pii: {
- fields: ['extracted_text'],
- starterPatterns: [],
- customPatterns: [{ id: 'private', label: 'private value', regex: privateText }],
- },
- },
+ it('does not count retained text-only history against endpoint file limits', async () => {
+ client.options.resendFiles = false;
+ mockReq.config.fileConfig = {
+ fileContextCharLimit: 1_000_000,
+ endpoints: { agents: { fileLimit: 1 } },
};
- const historicalFile = makeTextFile('historical-file', 'history.txt', privateText);
- const storedMessages = [
- {
- messageId: 'file-message',
- parentMessageId: null,
- sender: 'User',
- role: 'user',
- text: 'Use the historical file.',
- fileContext: privateText,
- files: [{ file_id: 'historical-file' }],
- isCreatedByUser: true,
- },
- {
- messageId: 'safe-message',
- parentMessageId: 'file-message',
- sender: 'User',
- role: 'user',
- text: 'Safe retained turn',
- isCreatedByUser: true,
- },
- ];
- client.authorizedHistoricalFiles = new Map([['historical-file', historicalFile]]);
- client.message_file_map = { 'file-message': [historicalFile] };
- client.setModelBoundStoredMessages(storedMessages);
-
- await expect(client.buildMessages(storedMessages, 'safe-message', {}, {})).resolves.toEqual(
- expect.objectContaining({ prompt: expect.any(Array) }),
- );
- const callback = client.createModelBoundChatModelCallback();
- expect(() =>
- callback.handleChatModelStart(undefined, [
+ await expect(
+ client.buildMessages(
[
{
- role: 'human',
- content: 'Safe retained turn',
- additional_kwargs: { sourceMessageId: 'safe-message' },
+ messageId: 'historical-context-1',
+ parentMessageId: null,
+ sender: 'User',
+ text: 'First retained context.',
+ isCreatedByUser: true,
+ fileContext: 'first retained file context',
},
- ],
- ]),
- ).not.toThrow();
- expect(() =>
- callback.handleChatModelStart(undefined, [
- [
{
- role: 'human',
- content: 'Use the historical file.',
- additional_kwargs: { sourceMessageId: 'file-message' },
+ messageId: 'historical-context-2',
+ parentMessageId: 'historical-context-1',
+ sender: 'User',
+ text: 'Second retained context.',
+ isCreatedByUser: true,
+ fileContext: 'second retained file context',
+ },
+ {
+ messageId: 'msg-1',
+ parentMessageId: 'historical-context-2',
+ sender: 'User',
+ text: 'Continue.',
+ isCreatedByUser: true,
},
],
- ]),
- ).toThrow(expect.objectContaining({ code: 'content_filter_block' }));
+ 'msg-1',
+ {},
+ ),
+ ).resolves.toEqual(expect.objectContaining({ prompt: expect.any(Array) }));
});
- it('filters historical steer attachments only when their source survives pruning', async () => {
- const privateText = 'PRIVATE-STEER-FILE-CONTENT';
- mockReq.config.filters = {
- files: {
- pii: {
- fields: ['extracted_text'],
- starterPatterns: [],
- customPatterns: [{ id: 'private', label: 'private value', regex: privateText }],
- },
- },
- };
+ it('rejects combined historical and current bytes before either batch is encoded', async () => {
+ mockAgent.endpoint = 'Moonshot';
+ client.options.endpointType = EModelEndpoint.custom;
client.options.resendFiles = true;
- require('~/models').getFiles.mockResolvedValue([
- makeTextFile('steer-file', 'steer.txt', privateText),
- ]);
+ mockReq.config.fileConfig = {
+ endpoints: { Moonshot: { fileLimit: 10, totalSizeLimit: 1 } },
+ };
+ const first = {
+ ...makeUploadedFile('history-1', 'one.pdf', 'application/pdf'),
+ bytes: 600_000,
+ };
+ const second = {
+ ...makeUploadedFile('current-1', 'two.pdf', 'application/pdf'),
+ bytes: 600_000,
+ };
+ client.options.attachments = Promise.resolve([second]);
+ require('~/models').getFiles.mockResolvedValue([first]);
+ client.addFileContextToMessage = jest.fn();
+ client.processAttachments = jest.fn();
- const storedMessages = await client.addPreviousAttachments([
- {
- messageId: 'assistant-msg',
- parentMessageId: null,
- isCreatedByUser: false,
- content: [
+ await expect(
+ client.addPreviousAttachments([
+ {
+ messageId: 'msg-1',
+ isCreatedByUser: true,
+ files: [{ file_id: first.file_id }],
+ },
+ ]),
+ ).rejects.toMatchObject({
+ code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED',
+ limitType: 'bytes',
+ });
+ expect(client.addFileContextToMessage).not.toHaveBeenCalled();
+ expect(client.processAttachments).not.toHaveBeenCalled();
+ });
+
+ it('rejects combined historical and scoped bytes before history is encoded', async () => {
+ mockAgent.endpoint = 'Moonshot';
+ client.options.endpointType = EModelEndpoint.custom;
+ client.options.resendFiles = true;
+ mockReq.config.fileConfig = {
+ endpoints: {
+ Moonshot: {
+ fileLimit: 10,
+ totalSizeLimit: 1,
+ supportedMimeTypes: ['^application/pdf$'],
+ },
+ },
+ };
+ const historicalFile = {
+ ...makeUploadedFile('history-1', 'history.pdf', 'application/pdf'),
+ bytes: 600_000,
+ };
+ const scopedFile = {
+ ...makeUploadedFile('scoped-1', 'scoped.pdf', 'application/pdf'),
+ bytes: 600_000,
+ };
+ client.options.agentContextAttachmentsByAgentId = new Map([['primary-agent', [scopedFile]]]);
+ require('~/models').getFiles.mockResolvedValue([historicalFile]);
+ client.addFileContextToMessage = jest.fn();
+ client.processAttachments = jest.fn();
+
+ await expect(
+ client.addPreviousAttachments([
+ {
+ messageId: 'msg-1',
+ isCreatedByUser: true,
+ files: [{ file_id: historicalFile.file_id }],
+ },
+ ]),
+ ).rejects.toMatchObject({
+ code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED',
+ limitType: 'bytes',
+ });
+ expect(client.addFileContextToMessage).not.toHaveBeenCalled();
+ expect(client.processAttachments).not.toHaveBeenCalled();
+ });
+
+ it('does not count display-only historical artifacts toward model attachment limits', async () => {
+ client.options.resendFiles = true;
+ const artifacts = Array.from({ length: 11 }, (_, index) =>
+ makeUploadedFile(`artifact-${index}`, `artifact-${index}.png`, 'image/png'),
+ );
+ require('~/models').getFiles.mockResolvedValue(artifacts);
+
+ await expect(
+ client.addPreviousAttachments([
+ {
+ messageId: 'assistant-artifacts',
+ isCreatedByUser: false,
+ attachments: artifacts.map(({ file_id }) => ({ file_id })),
+ },
+ ]),
+ ).resolves.toEqual([
+ expect.objectContaining({ attachments: expect.arrayContaining(artifacts) }),
+ ]);
+ });
+
+ it('does not admit endpoint-incompatible historical files to model limits', async () => {
+ mockAgent.endpoint = 'Moonshot';
+ client.options.endpointType = EModelEndpoint.custom;
+ client.options.resendFiles = true;
+ mockReq.config.fileConfig = {
+ endpoints: {
+ Moonshot: { fileLimit: 10, supportedMimeTypes: ['^text/plain$'] },
+ },
+ };
+ const incompatibleFiles = Array.from({ length: 11 }, (_, index) =>
+ makeUploadedFile(`history-${index}`, `history-${index}.bin`, 'application/octet-stream'),
+ );
+ require('~/models').getFiles.mockResolvedValue(incompatibleFiles);
+ client.addFileContextToMessage = jest.fn();
+ client.processAttachments = jest.fn();
+
+ await expect(
+ client.addPreviousAttachments(
+ incompatibleFiles.map((file, index) => ({
+ messageId: `msg-${index}`,
+ isCreatedByUser: true,
+ files: [{ file_id: file.file_id }],
+ })),
+ ),
+ ).resolves.toHaveLength(11);
+ expect(Object.values(client.message_file_map).flat()).toEqual([]);
+ expect(client.processAttachments).not.toHaveBeenCalled();
+ });
+
+ it('does not admit tool-only historical files to model limits', async () => {
+ client.options.resendFiles = true;
+ const toolFiles = Array.from({ length: 11 }, (_, index) => ({
+ ...makeUploadedFile(`tool-history-${index}`, `tool-${index}.txt`, 'text/plain'),
+ embedded: true,
+ }));
+ require('~/models').getFiles.mockResolvedValue(toolFiles);
+ client.addFileContextToMessage = jest.fn();
+ client.processAttachments = jest.fn((_message, files) => files);
+
+ await expect(
+ client.addPreviousAttachments(
+ toolFiles.map((file, index) => ({
+ messageId: `tool-msg-${index}`,
+ isCreatedByUser: true,
+ files: [{ file_id: file.file_id }],
+ })),
+ ),
+ ).resolves.toHaveLength(11);
+ expect(Object.values(client.message_file_map).flat()).toEqual([]);
+ expect(client.addFileContextToMessage).not.toHaveBeenCalled();
+ expect(client.processAttachments).not.toHaveBeenCalled();
+ });
+
+ it('does not count current tool-only resources toward model attachment admission', async () => {
+ mockReq.config.fileConfig = { endpoints: { openAI: { fileLimit: 1 } } };
+ const toolFiles = Array.from({ length: 10 }, (_, index) => ({
+ ...makeUploadedFile(`tool-current-${index}`, `tool-${index}.txt`, 'text/plain'),
+ embedded: true,
+ }));
+ const modelFile = makeTextFile('model-current', 'model.txt', 'model context');
+ client.options.attachments = [...toolFiles, modelFile];
+
+ await expect(
+ client.buildMessages(
+ [
+ {
+ messageId: 'msg-1',
+ parentMessageId: null,
+ sender: 'User',
+ text: 'Use the available context.',
+ isCreatedByUser: true,
+ },
+ ],
+ 'msg-1',
+ {},
+ ),
+ ).resolves.toEqual(expect.objectContaining({ prompt: expect.any(Array) }));
+ expect(client.modelBoundCurrentFiles).toEqual([modelFile]);
+ });
+
+ it('processes only endpoint-admitted current files plus tool-only passthrough files', async () => {
+ mockReq.config.fileConfig = {
+ endpoints: { openAI: { fileSizeLimit: 1, supportedMimeTypes: ['^text/plain$'] } },
+ };
+ const oversized = {
+ ...makeUploadedFile('oversized', 'oversized.png', 'image/png'),
+ bytes: 2 * 1024 * 1024,
+ };
+ const oversizedText = {
+ ...makeTextFile('oversized-text', 'oversized.txt', 'must not reach the prompt'),
+ bytes: 2 * 1024 * 1024,
+ };
+ const toolOnly = {
+ ...makeUploadedFile('tool-only', 'tool.txt', 'text/plain'),
+ embedded: true,
+ };
+ const admitted = makeTextFile('admitted', 'admitted.txt', 'model context');
+ client.options.attachments = [oversized, oversizedText, toolOnly, admitted];
+ client.addFileContextToMessage = jest.fn();
+ client.processAttachments = jest.fn((_message, files) => files);
+
+ await client.buildMessages(
+ [
+ {
+ messageId: 'msg-1',
+ parentMessageId: null,
+ sender: 'User',
+ text: 'Use the available context.',
+ isCreatedByUser: true,
+ },
+ ],
+ 'msg-1',
+ {},
+ );
+
+ expect(client.addFileContextToMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ messageId: 'msg-1' }),
+ [admitted],
+ );
+ expect(client.processAttachments).toHaveBeenCalledWith(
+ expect.objectContaining({ messageId: 'msg-1' }),
+ [toolOnly, admitted],
+ );
+ expect(client.options.attachments).toEqual([toolOnly, admitted]);
+ expect(client.message_file_map['msg-1']).toEqual([toolOnly, admitted]);
+ });
+
+ it('defers current attachment persistence until model admission', () => {
+ client.modelBoundCurrentFiles = [makeTextFile('pending', 'pending.txt', 'context')];
+
+ expect(client.shouldDeferUserMessagePersistence()).toBe(true);
+ });
+
+ it('keeps repeated lazy scoped-text admission cumulative across resolutions', () => {
+ mockReq.config.fileConfig = { fileContextCharLimit: 1_000_000 };
+ const repeated = makeTextFile('lazy-context', 'lazy.txt', 'x'.repeat(600_000));
+ const cumulativeInjections = [repeated];
+
+ expect(() => client.assertTurnAttachmentLimits([], cumulativeInjections)).not.toThrow();
+ cumulativeInjections.push(repeated);
+ expect(() => client.assertTurnAttachmentLimits([], cumulativeInjections)).toThrow(
+ expect.objectContaining({
+ code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED',
+ limitType: 'extracted_text',
+ }),
+ );
+ });
+
+ it('keeps live steer attachments cumulative with the initial turn', () => {
+ const initial = {
+ ...makeUploadedFile('initial-large', 'initial.pdf', 'application/pdf'),
+ bytes: 120 * 1024 * 1024,
+ };
+ const steer = {
+ ...makeUploadedFile('steer-large', 'steer.pdf', 'application/pdf'),
+ bytes: 20 * 1024 * 1024,
+ };
+ client.turnSharedAttachmentFiles = [initial];
+ client.turnScopedAttachmentsByAgentId = new Map([['primary-agent', []]]);
+ client.turnAttachmentEndpointsByAgentId = new Map([
+ ['primary-agent', { endpoint: mockAgent.endpoint }],
+ ]);
+
+ expect(() => client.admitSteerAttachments([steer])).toThrow(
+ expect.objectContaining({
+ code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED',
+ limitType: 'bytes',
+ }),
+ );
+ expect(client.turnSharedAttachmentFiles).toEqual([initial]);
+ });
+
+ it('does not charge tool-only steer files to model attachment admission', () => {
+ const toolOnly = {
+ ...makeUploadedFile('steer-tool-only', 'tool-only.bin', 'application/octet-stream'),
+ embedded: true,
+ bytes: 200 * 1024 * 1024,
+ };
+ client.turnSharedAttachmentFiles = [];
+ client.turnScopedAttachmentsByAgentId = new Map([['primary-agent', []]]);
+ client.turnAttachmentEndpointsByAgentId = new Map([
+ ['primary-agent', { endpoint: mockAgent.endpoint }],
+ ]);
+
+ expect(() => client.admitSteerAttachments([toolOnly])).not.toThrow();
+ expect(client.turnSharedAttachmentFiles).toEqual([]);
+ });
+
+ it('excludes tool-only and endpoint-incompatible scoped files from cumulative admission', () => {
+ mockAgent.endpoint = 'Moonshot';
+ client.options.endpointType = EModelEndpoint.custom;
+ mockReq.config.fileConfig = {
+ endpoints: {
+ Moonshot: { fileLimit: 1, supportedMimeTypes: ['^text/plain$'] },
+ },
+ };
+ const filtered = client.getFilteredScopedAttachmentMap(
+ new Set(),
+ new Map([
+ [
+ 'primary-agent',
+ [
+ {
+ ...makeUploadedFile('tool-only', 'tool.txt', 'text/plain'),
+ embedded: true,
+ },
+ makeUploadedFile('unsupported', 'unsupported.bin', 'application/octet-stream'),
+ makeTextFile('model-bound', 'model.txt', 'model context'),
+ ],
+ ],
+ ]),
+ [mockAgent],
+ );
+
+ expect([...filtered.values()].flat()).toEqual([
+ expect.objectContaining({ file_id: 'model-bound' }),
+ ]);
+ expect(() =>
+ client.assertTurnAttachmentLimits([], [...filtered.values()].flat()),
+ ).not.toThrow();
+ });
+
+ it('filters historical attachment content only when its source survives pruning', async () => {
+ const privateText = 'PRIVATE-HISTORICAL-CONTENT';
+ mockReq.config.filters = {
+ files: {
+ pii: {
+ fields: ['extracted_text'],
+ starterPatterns: [],
+ customPatterns: [{ id: 'private', label: 'private value', regex: privateText }],
+ },
+ },
+ };
+ client.options.resendFiles = true;
+ require('~/models').getFiles.mockResolvedValue([
+ makeTextFile('historical-file', 'history.txt', privateText),
+ ]);
+ client.addFileContextToMessage = jest.fn();
+ client.processAttachments = jest.fn((_message, files) => files);
+
+ const hydratedMessages = await client.addPreviousAttachments([
+ {
+ messageId: 'msg-1',
+ parentMessageId: null,
+ isCreatedByUser: true,
+ files: [{ file_id: 'historical-file' }],
+ },
+ ]);
+ client.setModelBoundStoredMessages([
+ ...hydratedMessages,
+ {
+ messageId: 'safe-message',
+ role: 'user',
+ text: 'Safe retained turn',
+ isCreatedByUser: true,
+ },
+ ]);
+ const callback = client.createModelBoundChatModelCallback();
+
+ expect(() =>
+ callback.handleChatModelStart(undefined, [
+ [
+ {
+ role: 'human',
+ content: 'Safe retained turn',
+ additional_kwargs: { sourceMessageId: 'safe-message' },
+ },
+ ],
+ ]),
+ ).not.toThrow();
+ expect(() =>
+ callback.handleChatModelStart(undefined, [
+ [
+ {
+ role: 'human',
+ content: 'Use the historical file.',
+ additional_kwargs: { sourceMessageId: 'msg-1' },
+ },
+ ],
+ ]),
+ ).toThrow(expect.objectContaining({ code: 'content_filter_block' }));
+
+ expect(client.addFileContextToMessage).toHaveBeenCalled();
+ expect(client.processAttachments).toHaveBeenCalled();
+ });
+
+ it('does not run historical file contexts through the pre-pruning build preflight', async () => {
+ const privateText = 'PRIVATE-PRUNED-HISTORICAL-FILE';
+ mockReq.config.filters = {
+ files: {
+ pii: {
+ fields: ['extracted_text'],
+ starterPatterns: [],
+ customPatterns: [{ id: 'private', label: 'private value', regex: privateText }],
+ },
+ },
+ };
+ const historicalFile = makeTextFile('historical-file', 'history.txt', privateText);
+ const storedMessages = [
+ {
+ messageId: 'file-message',
+ parentMessageId: null,
+ sender: 'User',
+ role: 'user',
+ text: 'Use the historical file.',
+ fileContext: privateText,
+ files: [{ file_id: 'historical-file' }],
+ isCreatedByUser: true,
+ },
+ {
+ messageId: 'safe-message',
+ parentMessageId: 'file-message',
+ sender: 'User',
+ role: 'user',
+ text: 'Safe retained turn',
+ isCreatedByUser: true,
+ },
+ ];
+ client.authorizedHistoricalFiles = new Map([['historical-file', historicalFile]]);
+ client.message_file_map = { 'file-message': [historicalFile] };
+ client.setModelBoundStoredMessages(storedMessages);
+
+ await expect(client.buildMessages(storedMessages, 'safe-message', {}, {})).resolves.toEqual(
+ expect.objectContaining({ prompt: expect.any(Array) }),
+ );
+
+ const callback = client.createModelBoundChatModelCallback();
+ expect(() =>
+ callback.handleChatModelStart(undefined, [
+ [
+ {
+ role: 'human',
+ content: 'Safe retained turn',
+ additional_kwargs: { sourceMessageId: 'safe-message' },
+ },
+ ],
+ ]),
+ ).not.toThrow();
+ expect(() =>
+ callback.handleChatModelStart(undefined, [
+ [
+ {
+ role: 'human',
+ content: 'Use the historical file.',
+ additional_kwargs: { sourceMessageId: 'file-message' },
+ },
+ ],
+ ]),
+ ).toThrow(expect.objectContaining({ code: 'content_filter_block' }));
+ });
+
+ it('filters historical steer attachments only when their source survives pruning', async () => {
+ const privateText = 'PRIVATE-STEER-FILE-CONTENT';
+ mockReq.config.filters = {
+ files: {
+ pii: {
+ fields: ['extracted_text'],
+ starterPatterns: [],
+ customPatterns: [{ id: 'private', label: 'private value', regex: privateText }],
+ },
+ },
+ };
+ client.options.resendFiles = true;
+ require('~/models').getFiles.mockResolvedValue([
+ makeTextFile('steer-file', 'steer.txt', privateText),
+ ]);
+
+ const storedMessages = await client.addPreviousAttachments([
+ {
+ messageId: 'assistant-msg',
+ parentMessageId: null,
+ isCreatedByUser: false,
+ content: [
{
type: ContentTypes.STEER,
steer: 'Read the attached file.',
@@ -5897,6 +6426,54 @@ describe('AgentClient - titleConvo', () => {
}),
);
});
+
+ it('keeps historical steer files in cumulative admission for lazy agents', async () => {
+ const historicalSteerFile = {
+ ...makeUploadedFile('steer-history', 'steer.pdf', 'application/pdf'),
+ bytes: 120 * 1024 * 1024,
+ };
+ const childContext = {
+ ...makeUploadedFile('lazy-context', 'lazy.pdf', 'application/pdf'),
+ bytes: 20 * 1024 * 1024,
+ };
+ const resolvedChild = {
+ id: 'lazy-child-agent',
+ endpoint: EModelEndpoint.openAI,
+ provider: EModelEndpoint.openAI,
+ instructions: 'Lazy child instructions',
+ model_parameters: { model: 'gpt-4' },
+ tools: [],
+ agentContextAttachments: [childContext],
+ };
+ const descriptor = {
+ id: resolvedChild.id,
+ resolve: jest.fn().mockResolvedValue(resolvedChild),
+ };
+ client.modelBoundHistoricalSteerFiles = [historicalSteerFile];
+ mockAgent.lazySubagentConfigs = [descriptor];
+ client.agentConfigs = new Map();
+
+ await client.buildMessages(
+ [
+ {
+ messageId: 'msg-1',
+ parentMessageId: null,
+ sender: 'User',
+ text: 'Answer from the child context.',
+ isCreatedByUser: true,
+ },
+ ],
+ 'msg-1',
+ {},
+ );
+
+ await expect(
+ descriptor.resolve({ signal: new AbortController().signal }),
+ ).rejects.toMatchObject({
+ code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED',
+ limitType: 'bytes',
+ });
+ });
});
describe('provider-native YouTube file preflight', () => {
@@ -7851,7 +8428,10 @@ describe('AgentClient - resumeCompletion content protection', () => {
expect(mockCreateRun.mock.calls[0][0]).toEqual(
expect.objectContaining({
tenantId: 'request-tenant',
- modelCallbacks: [expect.objectContaining({ name: 'librechat-model-bound-content-filter' })],
+ modelCallbacks: expect.arrayContaining([
+ expect.objectContaining({ name: 'librechat-model-bound-content-filter' }),
+ expect.objectContaining({ name: 'librechat-agent-attachment-memory' }),
+ ]),
compactionSemanticIndex: compactionSemanticIndex.entries,
}),
);
@@ -8013,7 +8593,11 @@ describe('AgentClient - resumeCompletion content protection', () => {
it('freezes owner-hydrated resume files into the final model callback', async () => {
mockGetAgentCheckpointer.mockResolvedValue({
getTuple: jest.fn().mockResolvedValue({
- checkpoint: { channel_values: { messages: [] } },
+ checkpoint: {
+ channel_values: {
+ messages: [{ role: 'human', files: [{ file_id: 'file-paused' }] }],
+ },
+ },
}),
});
const storedMessage = {
@@ -8029,6 +8613,9 @@ describe('AgentClient - resumeCompletion content protection', () => {
{
file_id: 'file-paused',
filename: 'report.txt',
+ source: 'text',
+ type: 'text/plain',
+ bytes: 10,
text: 'Safe extracted text',
},
]);
@@ -8049,7 +8636,19 @@ describe('AgentClient - resumeCompletion content protection', () => {
storedMessages: [storedMessage],
});
- const [modelBoundCallback] = mockCreateRun.mock.calls[0][0].modelCallbacks;
+ const [modelBoundCallback, attachmentMemoryCallback] =
+ mockCreateRun.mock.calls[0][0].modelCallbacks;
+ expect(attachmentMemoryCallback).toEqual(
+ expect.objectContaining({ name: 'librechat-agent-attachment-memory' }),
+ );
+ expect(context.attachmentMemoryContext).toEqual(
+ expect.objectContaining({
+ conversationId: 'conversation-123',
+ messageId: 'response-123',
+ attachments: [expect.objectContaining({ file_id: 'file-paused' })],
+ countRepeatedExtractedText: true,
+ }),
+ );
expect(() =>
modelBoundCallback.handleChatModelStart(undefined, [
[
@@ -8063,6 +8662,454 @@ describe('AgentClient - resumeCompletion content protection', () => {
).not.toThrow();
});
+ it('reapplies aggregate attachment limits to persistent history on resume', async () => {
+ const historicalFiles = Array.from({ length: 11 }, (_, index) => ({
+ file_id: `resume-history-${index}`,
+ filename: `history-${index}.txt`,
+ source: 'text',
+ type: 'text/plain',
+ text: 'context',
+ bytes: 10,
+ }));
+ require('~/models').getMessages.mockResolvedValue(
+ historicalFiles.map((file, index) => ({
+ messageId: index === historicalFiles.length - 1 ? 'parent-123' : `history-${index}`,
+ parentMessageId: index === 0 ? Constants.NO_PARENT : `history-${index - 1}`,
+ isCreatedByUser: true,
+ role: 'user',
+ text: 'inspect file',
+ files: [{ file_id: file.file_id }],
+ })),
+ );
+ require('~/models').getFiles.mockResolvedValue(historicalFiles);
+ mockGetAgentCheckpointer.mockResolvedValue({
+ getTuple: jest.fn().mockResolvedValue({
+ checkpoint: {
+ channel_values: {
+ messages: historicalFiles.map((file) => ({
+ role: 'human',
+ files: [{ file_id: file.file_id }],
+ })),
+ },
+ },
+ }),
+ });
+ const context = makeContext(undefined);
+ context.options.req.body.isTemporary = false;
+ context.options.req.config.fileConfig = {
+ endpoints: { agents: { fileLimit: 10 } },
+ };
+
+ await expect(
+ AgentClient.prototype.resumeCompletion.call(context, { resumeValue: {} }),
+ ).rejects.toMatchObject({
+ code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED',
+ limitType: 'count',
+ });
+ expect(mockCreateRun).not.toHaveBeenCalled();
+ });
+
+ it('counts a restored request file only once when it is already in the checkpoint', async () => {
+ const retainedFile = {
+ file_id: 'retained-request',
+ filename: 'retained.txt',
+ source: 'text',
+ type: 'text/plain',
+ text: 'x'.repeat(600_000),
+ bytes: 600_000,
+ };
+ mockGetAgentCheckpointer.mockResolvedValue({
+ getTuple: jest.fn().mockResolvedValue({
+ checkpoint: {
+ channel_values: {
+ messages: [{ role: 'human', files: [{ file_id: retainedFile.file_id }] }],
+ },
+ },
+ }),
+ });
+ require('~/models').getFiles.mockResolvedValue([retainedFile]);
+ const resume = jest.fn().mockResolvedValue(undefined);
+ mockCreateRun.mockResolvedValue({ resume, getCalibrationRatio: jest.fn(() => 0) });
+ const context = makeContext(undefined);
+ context.options.attachments = [retainedFile];
+ context.options.req.config.fileConfig = { fileContextCharLimit: 1_000_000 };
+
+ await expect(
+ AgentClient.prototype.resumeCompletion.call(context, { resumeValue: {} }),
+ ).resolves.toBeUndefined();
+
+ expect(mockCreateRun).toHaveBeenCalledTimes(1);
+ expect(context.attachmentMemoryContext.attachments).toEqual([retainedFile]);
+ });
+
+ it('limits resume history to files retained by the checkpoint', async () => {
+ const historicalFiles = Array.from({ length: 11 }, (_, index) => ({
+ file_id: `old-history-${index}`,
+ filename: `old-${index}.txt`,
+ source: 'text',
+ type: 'text/plain',
+ text: 'context',
+ bytes: 10,
+ }));
+ mockGetAgentCheckpointer.mockResolvedValue({
+ getTuple: jest.fn().mockResolvedValue({
+ checkpoint: {
+ channel_values: {
+ messages: [{ role: 'human', files: [{ file_id: 'old-history-10' }] }],
+ },
+ },
+ }),
+ });
+ require('~/models').getFiles.mockResolvedValue(historicalFiles);
+ const resume = jest.fn().mockResolvedValue(undefined);
+ mockCreateRun.mockResolvedValue({ resume, getCalibrationRatio: jest.fn(() => 0) });
+ const context = makeContext(undefined);
+ context.options.req.config.fileConfig = {
+ endpoints: { agents: { fileLimit: 10 } },
+ };
+
+ await AgentClient.prototype.resumeCompletion.call(context, { resumeValue: {} });
+
+ expect(mockCreateRun).toHaveBeenCalledTimes(1);
+ expect(context.attachmentMemoryContext.attachments).toEqual([
+ expect.objectContaining({ file_id: 'old-history-10' }),
+ ]);
+ });
+
+ it('counts checkpoint files retained in model state after endpoint policy tightens', async () => {
+ const checkpointFiles = [
+ {
+ file_id: 'retained-1',
+ filename: 'retained-1.pdf',
+ source: 'local',
+ type: 'application/pdf',
+ bytes: 10,
+ },
+ {
+ file_id: 'retained-2',
+ filename: 'retained-2.pdf',
+ source: 'local',
+ type: 'application/pdf',
+ bytes: 10,
+ },
+ ];
+ mockGetAgentCheckpointer.mockResolvedValue({
+ getTuple: jest.fn().mockResolvedValue({
+ checkpoint: {
+ channel_values: {
+ messages: [
+ {
+ role: 'human',
+ files: checkpointFiles.map(({ file_id }) => ({ file_id })),
+ },
+ ],
+ },
+ },
+ }),
+ });
+ require('~/models').getFiles.mockResolvedValue(checkpointFiles);
+ const context = makeContext(undefined);
+ context.options.req.config.fileConfig = {
+ endpoints: {
+ agents: { fileLimit: 1 },
+ },
+ };
+
+ await expect(
+ AgentClient.prototype.resumeCompletion.call(context, { resumeValue: {} }),
+ ).rejects.toMatchObject({
+ code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED',
+ limitType: 'count',
+ });
+ expect(mockCreateRun).not.toHaveBeenCalled();
+ });
+
+ it('reapplies each secondary agent endpoint limit on resume', async () => {
+ mockGetAgentCheckpointer.mockResolvedValue({
+ getTuple: jest.fn().mockResolvedValue({
+ checkpoint: { channel_values: { messages: [] } },
+ }),
+ });
+ const context = makeContext(undefined);
+ context.options.agent.endpoint = 'openAI';
+ context.options.req.config.fileConfig = {
+ endpoints: {
+ openAI: { fileLimit: 10 },
+ Moonshot: { fileLimit: 1, supportedMimeTypes: ['^text/plain$'] },
+ },
+ };
+ context.agentConfigs = new Map([
+ [
+ 'secondary',
+ {
+ id: 'secondary',
+ endpoint: 'Moonshot',
+ model_parameters: { model: 'moonshot-v1' },
+ tools: [],
+ },
+ ],
+ ]);
+ context.options.agentContextAttachmentsByAgentId = new Map([
+ [
+ 'secondary',
+ [
+ { file_id: 'secondary-1', source: 'text', type: 'text/plain', text: 'one', bytes: 1 },
+ { file_id: 'secondary-2', source: 'text', type: 'text/plain', text: 'two', bytes: 1 },
+ ],
+ ],
+ ]);
+
+ await expect(
+ AgentClient.prototype.resumeCompletion.call(context, { resumeValue: {} }),
+ ).rejects.toMatchObject({
+ code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED',
+ limitType: 'count',
+ observed: 2,
+ limit: 1,
+ });
+ expect(mockCreateRun).not.toHaveBeenCalled();
+ });
+
+ it('restores agent-scoped file context before rebuilding a resumed run', async () => {
+ mockGetAgentCheckpointer.mockResolvedValue({
+ getTuple: jest.fn().mockResolvedValue({
+ checkpoint: { channel_values: { messages: [] } },
+ }),
+ });
+ const resume = jest.fn().mockResolvedValue(undefined);
+ mockCreateRun.mockResolvedValue({ resume, getCalibrationRatio: jest.fn(() => 0) });
+ const context = makeContext(undefined);
+ context.options.agentContextAttachmentsByAgentId = new Map([
+ [
+ 'agent-123',
+ [
+ {
+ file_id: 'resume-private-context',
+ filename: 'private.txt',
+ source: 'text',
+ type: 'text/plain',
+ text: 'Resume-only private context',
+ bytes: 27,
+ },
+ ],
+ ],
+ ]);
+
+ await AgentClient.prototype.resumeCompletion.call(context, { resumeValue: {} });
+
+ expect(context.options.agent.additional_instructions).toContain('Resume-only private context');
+ expect(mockCreateRun).toHaveBeenCalledTimes(1);
+ });
+
+ it('reapplies shared attachment limits after a lazy resume agent resolves', async () => {
+ mockGetAgentCheckpointer.mockResolvedValue({
+ getTuple: jest.fn().mockResolvedValue({
+ checkpoint: { channel_values: { messages: [] } },
+ }),
+ });
+ const resolvedChild = {
+ id: 'lazy-secondary',
+ endpoint: 'Moonshot',
+ model_parameters: { model: 'moonshot-v1' },
+ tools: [],
+ };
+ const resolveLazy = jest.fn().mockResolvedValue(resolvedChild);
+ const descriptor = {
+ id: 'lazy-secondary',
+ resolve: resolveLazy,
+ };
+ const sharedFile = {
+ file_id: 'shared-large',
+ filename: 'shared.txt',
+ source: 'text',
+ type: 'text/plain',
+ text: 'shared context',
+ bytes: 2 * 1024 * 1024,
+ };
+ const context = makeContext(undefined);
+ context.options.agent.endpoint = 'openAI';
+ context.options.agent.lazySubagentConfigs = [descriptor];
+ context.options.attachments = [sharedFile];
+ context.options.req.config.fileConfig = {
+ endpoints: {
+ openAI: { totalSizeLimit: 128 },
+ Moonshot: { totalSizeLimit: 1 },
+ },
+ };
+ mockCreateRun.mockImplementation(async () => ({
+ resume: jest.fn(async () => descriptor.resolve({ signal: new AbortController().signal })),
+ getCalibrationRatio: jest.fn(() => 0),
+ }));
+
+ await expect(
+ AgentClient.prototype.resumeCompletion.call(context, { resumeValue: {} }),
+ ).rejects.toMatchObject({
+ code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED',
+ limitType: 'bytes',
+ observed: 2 * 1024 * 1024,
+ limit: 1024 * 1024,
+ });
+ expect(resolveLazy).toHaveBeenCalledTimes(1);
+ });
+
+ it('includes admitted steer files when a lazy resume agent resolves', async () => {
+ mockGetAgentCheckpointer.mockResolvedValue({
+ getTuple: jest.fn().mockResolvedValue({
+ checkpoint: { channel_values: { messages: [] } },
+ }),
+ });
+ const resolvedChild = {
+ id: 'lazy-secondary',
+ endpoint: 'Moonshot',
+ model_parameters: { model: 'moonshot-v1' },
+ tools: [],
+ };
+ const descriptor = {
+ id: 'lazy-secondary',
+ resolve: jest.fn().mockResolvedValue(resolvedChild),
+ };
+ const steerFile = {
+ file_id: 'steer-large',
+ filename: 'steer.txt',
+ source: 'text',
+ type: 'text/plain',
+ text: 'steered context',
+ bytes: 2 * 1024 * 1024,
+ };
+ const context = makeContext(undefined);
+ context.options.agent.endpoint = 'openAI';
+ context.options.agent.lazySubagentConfigs = [descriptor];
+ context.options.req.config.fileConfig = {
+ endpoints: {
+ openAI: { totalSizeLimit: 128 },
+ Moonshot: { totalSizeLimit: 1 },
+ },
+ };
+ mockCreateRun.mockImplementation(async () => ({
+ resume: jest.fn(async () => {
+ context.turnSharedAttachmentFiles.push(steerFile);
+ return descriptor.resolve({ signal: new AbortController().signal });
+ }),
+ getCalibrationRatio: jest.fn(() => 0),
+ }));
+
+ await expect(
+ AgentClient.prototype.resumeCompletion.call(context, { resumeValue: {} }),
+ ).rejects.toMatchObject({
+ code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED',
+ limitType: 'bytes',
+ observed: 2 * 1024 * 1024,
+ limit: 1024 * 1024,
+ });
+ });
+
+ it('reserves a lazy resume endpoint before awaiting its scoped context', async () => {
+ mockGetAgentCheckpointer.mockResolvedValue({
+ getTuple: jest.fn().mockResolvedValue({
+ checkpoint: { channel_values: { messages: [] } },
+ }),
+ });
+ const resolvedChild = {
+ id: 'lazy-secondary',
+ endpoint: 'Moonshot',
+ model_parameters: { model: 'moonshot-v1' },
+ tools: [],
+ };
+ const descriptor = {
+ id: 'lazy-secondary',
+ resolve: jest.fn().mockResolvedValue(resolvedChild),
+ };
+ const lateScopedContext = deferred();
+ mockBuildAgentScopedContext.mockImplementationOnce((...args) =>
+ jest.requireActual('@librechat/api').buildAgentScopedContext(...args),
+ );
+ mockBuildAgentScopedContext.mockImplementationOnce(() => lateScopedContext.promise);
+ const context = makeContext(undefined);
+ context.options.agent.endpoint = 'openAI';
+ context.options.agent.lazySubagentConfigs = [descriptor];
+ context.options.req.config.fileConfig = {
+ endpoints: {
+ openAI: { totalSizeLimit: 128 },
+ Moonshot: { totalSizeLimit: 1 },
+ },
+ };
+ mockCreateRun.mockImplementation(async () => ({
+ resume: jest.fn(async () => descriptor.resolve({ signal: new AbortController().signal })),
+ getCalibrationRatio: jest.fn(() => 0),
+ }));
+
+ const resumePromise = AgentClient.prototype.resumeCompletion.call(context, { resumeValue: {} });
+ for (
+ let attempt = 0;
+ attempt < 20 && mockBuildAgentScopedContext.mock.calls.length < 2;
+ attempt++
+ ) {
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+
+ expect(mockBuildAgentScopedContext).toHaveBeenCalledTimes(2);
+ expect(() =>
+ AgentClient.prototype.admitSteerAttachments.call(context, [
+ {
+ file_id: 'racing-steer',
+ filename: 'racing.txt',
+ source: 'text',
+ type: 'text/plain',
+ text: 'steered context',
+ bytes: 2 * 1024 * 1024,
+ },
+ ]),
+ ).toThrow(
+ expect.objectContaining({
+ code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED',
+ limitType: 'bytes',
+ }),
+ );
+
+ lateScopedContext.resolve(new Map([['lazy-secondary', '']]));
+ await expect(resumePromise).resolves.toBeUndefined();
+ });
+
+ it('restores scoped file context after a lazy resume agent resolves', async () => {
+ mockGetAgentCheckpointer.mockResolvedValue({
+ getTuple: jest.fn().mockResolvedValue({
+ checkpoint: { channel_values: { messages: [] } },
+ }),
+ });
+ const resolvedChild = {
+ id: 'lazy-secondary',
+ endpoint: 'Moonshot',
+ model_parameters: { model: 'moonshot-v1' },
+ tools: [],
+ agentContextAttachments: [
+ {
+ file_id: 'lazy-private-context',
+ filename: 'lazy-private.txt',
+ source: 'text',
+ type: 'text/plain',
+ text: 'Lazy resume private context',
+ bytes: 27,
+ },
+ ],
+ };
+ const resolveLazy = jest.fn().mockResolvedValue(resolvedChild);
+ const descriptor = {
+ id: 'lazy-secondary',
+ resolve: resolveLazy,
+ };
+ const context = makeContext(undefined);
+ context.options.agent.lazySubagentConfigs = [descriptor];
+ mockCreateRun.mockImplementation(async () => ({
+ resume: jest.fn(async () => descriptor.resolve({ signal: new AbortController().signal })),
+ getCalibrationRatio: jest.fn(() => 0),
+ }));
+
+ await AgentClient.prototype.resumeCompletion.call(context, { resumeValue: {} });
+
+ expect(resolvedChild.additional_instructions).toContain('Lazy resume private context');
+ expect(resolveLazy).toHaveBeenCalledTimes(1);
+ });
+
it('fails closed when a paused file reference cannot be rehydrated', async () => {
mockGetAgentCheckpointer.mockResolvedValue({
getTuple: jest.fn().mockResolvedValue({
diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.js
index 48ae4831c6..2a6c920fca 100644
--- a/api/server/controllers/agents/openai.js
+++ b/api/server/controllers/agents/openai.js
@@ -1057,6 +1057,10 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {
agentIds: contextAgents.map(({ id }) => id),
attachmentsByAgentId: buildAgentContextAttachmentsByAgentId(contextAgents),
req,
+ endpoint: primaryConfig.endpoint,
+ endpointsByAgentId: new Map(
+ contextAgents.map((runAgent) => [runAgent.id, { endpoint: runAgent.endpoint }]),
+ ),
});
const mcpManager = getMCPManager();
const configServers = await resolveConfigServers(req);
diff --git a/api/server/controllers/agents/request.js b/api/server/controllers/agents/request.js
index b1bdd555cd..a1bf9bdcc6 100644
--- a/api/server/controllers/agents/request.js
+++ b/api/server/controllers/agents/request.js
@@ -40,6 +40,7 @@ const {
isHITLEnabled,
agentRequestsAskUserQuestion,
resolveAgentTurnExecutionPlan,
+ logAgentMemorySnapshot,
} = require('@librechat/api');
const { disposeClient } = require('~/server/cleanup');
const {
@@ -2721,6 +2722,17 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit
expiredAt: req?._agentEventBindingRetention?.expiredAt,
interfaceConfig: req?.config?.interfaceConfig,
};
+ const terminalMemoryContext = {
+ ...(client?.attachmentMemoryContext ?? {}),
+ req,
+ conversationId: conversation?.conversationId,
+ messageId: response?.messageId,
+ attachments:
+ client?.attachmentMemoryContext?.attachments ??
+ client?.modelBoundCurrentFiles ??
+ req.body.files,
+ };
+ logAgentMemorySnapshot('before_terminal_save', terminalMemoryContext);
if (!client.skipSaveUserMessage) {
if (!userMessage) {
@@ -2773,6 +2785,7 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit
: 'Response message could not be persisted before terminal publication',
);
}
+ logAgentMemorySnapshot('after_terminal_save', terminalMemoryContext);
if (appliedEventActor != null) {
const recorded = await recordAgentEventActorReconciliation({
user: userId,
@@ -2858,10 +2871,12 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit
);
terminalPublicationStarted = true;
+ logAgentMemorySnapshot('before_final_publish', terminalMemoryContext);
const publication = await GenerationJobManager.publishTerminalClaim(
terminalClaim,
finalEvent,
);
+ logAgentMemorySnapshot('after_final_publish', terminalMemoryContext);
let terminalOutcome = 'completed_without_delta';
if (publication.persistenceFailed) {
terminalOutcome = 'error';
diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.js
index dd6fb2e7d4..58bc81925e 100644
--- a/api/server/controllers/agents/responses.js
+++ b/api/server/controllers/agents/responses.js
@@ -998,6 +998,10 @@ const executeResponse = async (envelope, { req, res }) => {
agentIds: modelBoundAgents.map(({ id }) => id),
attachmentsByAgentId: agentContextAttachmentsByAgentId,
req,
+ endpoint: primaryConfig.endpoint,
+ endpointsByAgentId: new Map(
+ modelBoundAgents.map((runAgent) => [runAgent.id, { endpoint: runAgent.endpoint }]),
+ ),
});
const mcpManager = getMCPManager();
diff --git a/client/src/utils/__tests__/steer.spec.ts b/client/src/utils/__tests__/steer.spec.ts
index 85be846b4c..2dba4a24a2 100644
--- a/client/src/utils/__tests__/steer.spec.ts
+++ b/client/src/utils/__tests__/steer.spec.ts
@@ -64,6 +64,25 @@ describe('applySteerPart', () => {
expect(twice).toBe(once);
});
+ it('replaces a persisted steer when a later correction removes rejected files', () => {
+ const withFiles = applySteerPart(
+ assistantMessage(),
+ buildEvent({
+ part: {
+ type: ContentTypes.STEER,
+ [ContentTypes.STEER]: 'change course',
+ steerId: 'steer-1',
+ files: [{ file_id: 'rejected-file' }],
+ },
+ }),
+ );
+ const corrected = applySteerPart(withFiles, buildEvent());
+
+ expect(corrected).not.toBe(withFiles);
+ expect(getSteerPart(corrected.content?.[2])?.files).toBeUndefined();
+ expect(corrected.content).toHaveLength(3);
+ });
+
it('handles a message without content', () => {
const message = assistantMessage({ content: undefined });
const updated = applySteerPart(message, buildEvent({ index: 0 }));
diff --git a/client/src/utils/steer.ts b/client/src/utils/steer.ts
index 0703b50190..cf35ba84ab 100644
--- a/client/src/utils/steer.ts
+++ b/client/src/utils/steer.ts
@@ -158,6 +158,11 @@ export function applySteerPart(message: TMessage, event: TSteerAppliedEvent): TM
const content = Array.isArray(message.content) ? message.content : [];
const existing = getSteerPart(content[index] as TMessageContentParts | undefined);
if (existing != null && existing.steerId === part.steerId) {
+ if (existing.files?.length && !part.files?.length) {
+ const nextContent = [...content] as TMessageContentParts[];
+ nextContent[index] = part as TMessageContentParts;
+ return { ...message, content: nextContent };
+ }
return message;
}
const nextContent = [...content] as TMessageContentParts[];
diff --git a/librechat.example.yaml b/librechat.example.yaml
index c6b25bda42..4971db7e48 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -1013,7 +1013,11 @@ endpoints:
# tokens: 2000 # Also preserve up to this many recent tokens
# fileConfig:
+# fileContextSizeLimit: 128 # Maximum aggregate model-bound attachment size in one agent turn (MB)
+# fileContextCharLimit: 1000000 # Maximum aggregate extracted-text characters in one agent turn
# endpoints:
+# agents:
+# fileLimit: 10
# assistants:
# fileLimit: 5
# fileSizeLimit: 10 # Maximum size for an individual file in MB
diff --git a/packages/api/src/agents/__tests__/initialize.test.ts b/packages/api/src/agents/__tests__/initialize.test.ts
index 12893f331f..2fdb5d0183 100644
--- a/packages/api/src/agents/__tests__/initialize.test.ts
+++ b/packages/api/src/agents/__tests__/initialize.test.ts
@@ -1335,6 +1335,126 @@ describe('initializeAgent — attachment scoping', () => {
expect(result.agentContextAttachments).toEqual([agentContextFile]);
});
+ it('applies aggregate limits only to endpoint-compatible file survivors', async () => {
+ const { filterFilesByEndpointRuntimeConfig } = jest.requireMock('~/files') as {
+ filterFilesByEndpointRuntimeConfig: jest.Mock;
+ };
+ const incompatibleFiles = Array.from({ length: 11 }, (_, index) => ({
+ file_id: `incompatible-${index}`,
+ filename: `incompatible-${index}.bin`,
+ type: 'application/x-incompatible',
+ bytes: 1024,
+ })) as IMongoFile[];
+ const { agent, req, res, loadTools, db } = createMocks();
+ mockExtractLibreChatParams.mockReturnValueOnce({
+ resendFiles: true,
+ maxContextTokens: undefined,
+ modelOptions: { model: agent.model },
+ });
+ (db.getFiles as jest.Mock).mockResolvedValueOnce(incompatibleFiles);
+ filterFilesByEndpointRuntimeConfig.mockReturnValueOnce([]);
+
+ await expect(
+ initializeAgent(
+ {
+ req,
+ res,
+ agent,
+ loadTools,
+ requestFiles: incompatibleFiles,
+ endpointOption: { endpoint: EModelEndpoint.agents },
+ allowedProviders: new Set([Providers.OPENAI]),
+ isInitialAgent: true,
+ },
+ db,
+ ),
+ ).resolves.toBeDefined();
+ expect(filterFilesByEndpointRuntimeConfig).toHaveBeenCalledWith(
+ req.config,
+ expect.objectContaining({ files: incompatibleFiles }),
+ );
+ });
+
+ it('does not apply model attachment limits to tool-only workspace files', async () => {
+ const { filterFilesByEndpointRuntimeConfig } = jest.requireMock('~/files') as {
+ filterFilesByEndpointRuntimeConfig: jest.Mock;
+ };
+ const toolFiles = Array.from({ length: 11 }, (_, index) => ({
+ file_id: `tool-${index}`,
+ filename: `tool-${index}.txt`,
+ type: 'text/plain',
+ bytes: 1024,
+ })) as IMongoFile[];
+ const { agent, req, res, loadTools, db } = createMocks();
+ agent.tools = [EToolResources.file_search];
+ mockExtractLibreChatParams.mockReturnValueOnce({
+ resendFiles: true,
+ maxContextTokens: undefined,
+ modelOptions: { model: agent.model },
+ });
+ (db.getConvoFiles as jest.Mock).mockResolvedValueOnce(toolFiles.map((file) => file.file_id));
+ (db.getToolFilesByIds as jest.Mock).mockResolvedValueOnce(toolFiles);
+ (db.getFiles as jest.Mock).mockResolvedValueOnce(toolFiles);
+ filterFilesByEndpointRuntimeConfig.mockImplementationOnce(
+ (_config: ServerRequest['config'], { files }: { files: IMongoFile[] }) => files,
+ );
+
+ await expect(
+ initializeAgent(
+ {
+ req,
+ res,
+ agent,
+ loadTools,
+ conversationId: 'conversation-1',
+ endpointOption: { endpoint: EModelEndpoint.agents },
+ allowedProviders: new Set([Providers.OPENAI]),
+ isInitialAgent: true,
+ },
+ db,
+ ),
+ ).resolves.toBeDefined();
+ });
+
+ it('does not apply model attachment limits to a tool-only current request file', async () => {
+ const { filterFilesByEndpointRuntimeConfig } = jest.requireMock('~/files') as {
+ filterFilesByEndpointRuntimeConfig: jest.Mock;
+ };
+ const toolOnlyRequestFile = {
+ file_id: 'request-tool-only',
+ filename: 'workspace.bin',
+ type: 'application/octet-stream',
+ bytes: 200 * 1024 * 1024,
+ embedded: true,
+ } as IMongoFile;
+ const { agent, req, res, loadTools, db } = createMocks();
+ mockExtractLibreChatParams.mockReturnValueOnce({
+ resendFiles: true,
+ maxContextTokens: undefined,
+ modelOptions: { model: agent.model },
+ });
+ (db.getFiles as jest.Mock).mockResolvedValueOnce([toolOnlyRequestFile]);
+ filterFilesByEndpointRuntimeConfig.mockImplementationOnce(
+ (_config: ServerRequest['config'], { files }: { files: IMongoFile[] }) => files,
+ );
+
+ await expect(
+ initializeAgent(
+ {
+ req,
+ res,
+ agent,
+ loadTools,
+ requestFiles: [toolOnlyRequestFile],
+ endpointOption: { endpoint: EModelEndpoint.agents },
+ allowedProviders: new Set([Providers.OPENAI]),
+ isInitialAgent: true,
+ },
+ db,
+ ),
+ ).resolves.toBeDefined();
+ });
+
it('owner-scopes request file usage updates while preserving trusted tool files', async () => {
const { primeResources } = jest.requireMock('../resources') as {
primeResources: jest.Mock;
diff --git a/packages/api/src/agents/attachments.test.ts b/packages/api/src/agents/attachments.test.ts
index 9c2bfe639c..a7d6d64836 100644
--- a/packages/api/src/agents/attachments.test.ts
+++ b/packages/api/src/agents/attachments.test.ts
@@ -1,11 +1,23 @@
-import { FileSources } from 'librechat-data-provider';
+import { logger } from '@librechat/data-schemas';
+import { EModelEndpoint, FileSources } from 'librechat-data-provider';
import type { IMongoFile } from '@librechat/data-schemas';
import type { ServerRequest } from '~/types';
+
+jest.mock('@librechat/data-schemas', () => ({
+ logger: { info: jest.fn() },
+}));
+
import {
+ AgentAttachmentLimitError,
+ AgentAttachmentPolicyError,
+ assertAgentAttachmentLimits,
+ createAgentMemoryCallback,
+ collectAgentAttachmentStats,
collectFileIds,
buildAgentScopedContext,
getAgentContextAttachments,
buildAgentContextAttachmentsByAgentId,
+ isModelBoundAttachmentFile,
} from './attachments';
const makeTextFile = (file_id: string, filename: string, text: string): IMongoFile =>
@@ -13,10 +25,349 @@ const makeTextFile = (file_id: string, filename: string, text: string): IMongoFi
file_id,
filename,
text,
+ bytes: 0,
source: FileSources.text,
}) as IMongoFile;
describe('agent attachment helpers', () => {
+ it('excludes tool-only files while retaining extracted text files', () => {
+ expect(isModelBoundAttachmentFile({ file_id: 'rag', embedded: true } as IMongoFile)).toBe(
+ false,
+ );
+ expect(
+ isModelBoundAttachmentFile({
+ file_id: 'code',
+ metadata: { codeEnvRef: { file_id: 'code-file', storage_session_id: 'session' } },
+ } as IMongoFile),
+ ).toBe(false);
+ expect(
+ isModelBoundAttachmentFile({
+ file_id: 'text',
+ source: FileSources.text,
+ embedded: true,
+ text: 'injected context',
+ } as IMongoFile),
+ ).toBe(true);
+ expect(
+ isModelBoundAttachmentFile({
+ file_id: 'empty-text',
+ source: FileSources.text,
+ text: '',
+ } as IMongoFile),
+ ).toBe(false);
+ });
+
+ it('summarizes unique attachment bytes and extracted text', () => {
+ const stats = collectAgentAttachmentStats([
+ { file_id: 'file-1', bytes: 12, type: 'text/plain', text: 'hello' },
+ { file_id: 'file-1', bytes: 12, type: 'text/plain', text: 'hello' },
+ { file_id: 'file-2', bytes: 8, type: 'application/pdf', text: 'world!' },
+ ]);
+
+ expect(stats).toMatchObject({
+ attachmentCount: 2,
+ totalKnownBytes: 20,
+ extractedTextChars: 11,
+ });
+ expect(stats.files).toEqual([
+ { fileId: 'file-1', mimeType: 'text/plain', bytes: 12, extractedTextChars: 5 },
+ { fileId: 'file-2', mimeType: 'application/pdf', bytes: 8, extractedTextChars: 6 },
+ ]);
+ });
+
+ it('counts bytes once per repeated model injection when requested', () => {
+ const repeated = {
+ file_id: 'replayed-pdf',
+ bytes: 70 * 1024 * 1024,
+ type: 'application/pdf',
+ };
+
+ expect(() =>
+ assertAgentAttachmentLimits({
+ attachments: [repeated, repeated],
+ fileConfig: { fileContextSizeLimit: 128 },
+ countRepeatedExtractedText: true,
+ }),
+ ).toThrow(
+ expect.objectContaining({
+ limitType: 'bytes',
+ observed: 140 * 1024 * 1024,
+ }),
+ );
+ });
+
+ it.each([
+ {
+ name: 'attachment count',
+ files: [
+ { file_id: 'file-1', bytes: 1 },
+ { file_id: 'file-2', bytes: 1 },
+ ],
+ fileConfig: { endpoints: { agents: { fileLimit: 1 } } },
+ limitType: 'count',
+ },
+ {
+ name: 'aggregate bytes',
+ files: [{ file_id: 'file-1', bytes: 2 * 1024 * 1024 }],
+ fileConfig: { endpoints: { agents: { totalSizeLimit: 1 } } },
+ limitType: 'bytes',
+ },
+ {
+ name: 'aggregate extracted text',
+ files: [{ file_id: 'file-1', bytes: 1, text: 'too long' }],
+ fileConfig: { fileContextCharLimit: 4 },
+ limitType: 'extracted_text',
+ },
+ ])('rejects turns over the configured $name limit', ({ files, fileConfig, limitType }) => {
+ const req = { config: { fileConfig } };
+
+ expect(() => assertAgentAttachmentLimits({ attachments: files, req })).toThrow(
+ expect.objectContaining<Partial<AgentAttachmentLimitError>>({
+ code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED',
+ limitType: limitType as AgentAttachmentLimitError['limitType'],
+ }),
+ );
+ });
+
+ it('applies the context-size default to a provider-backed agent', () => {
+ expect(() =>
+ assertAgentAttachmentLimits({
+ attachments: [{ file_id: 'large', bytes: 200 * 1024 * 1024 }],
+ req: { config: {} },
+ endpoint: EModelEndpoint.openAI,
+ }),
+ ).toThrow(expect.objectContaining({ limitType: 'bytes' }));
+ });
+
+ it('falls back to the agents file limit for a provider-backed agent', () => {
+ expect(() =>
+ assertAgentAttachmentLimits({
+ attachments: [{ file_id: 'one' }, { file_id: 'two' }],
+ req: { config: { fileConfig: { endpoints: { agents: { fileLimit: 1 } } } } },
+ endpoint: EModelEndpoint.openAI,
+ }),
+ ).toThrow(expect.objectContaining({ limitType: 'count', observed: 2, limit: 1 }));
+ });
+
+ it('falls back to the agents file limit for a partial provider config', () => {
+ expect(() =>
+ assertAgentAttachmentLimits({
+ attachments: [{ file_id: 'one' }, { file_id: 'two' }],
+ req: {
+ config: {
+ fileConfig: {
+ endpoints: {
+ agents: { fileLimit: 1 },
+ openAI: { supportedMimeTypes: ['^text/plain$'] },
+ },
+ },
+ },
+ },
+ endpoint: EModelEndpoint.openAI,
+ }),
+ ).toThrow(expect.objectContaining({ limitType: 'count', observed: 2, limit: 1 }));
+ });
+
+ it('prefers an explicit backing-provider file limit over the agents fallback', () => {
+ expect(() =>
+ assertAgentAttachmentLimits({
+ attachments: [{ file_id: 'one' }, { file_id: 'two' }],
+ req: {
+ config: {
+ fileConfig: {
+ endpoints: { agents: { fileLimit: 1 }, openAI: { fileLimit: 2 } },
+ },
+ },
+ },
+ endpoint: EModelEndpoint.openAI,
+ }),
+ ).not.toThrow();
+ });
+
+ it('prefers the generic custom file limit over the agents fallback', () => {
+ expect(() =>
+ assertAgentAttachmentLimits({
+ attachments: [{ file_id: 'one' }, { file_id: 'two' }],
+ req: {
+ config: {
+ fileConfig: {
+ endpoints: { agents: { fileLimit: 10 }, custom: { fileLimit: 1 } },
+ },
+ },
+ },
+ endpoint: 'Moonshot',
+ }),
+ ).toThrow(expect.objectContaining({ limitType: 'count', observed: 2, limit: 1 }));
+ });
+
+ it('does not borrow a generic custom file limit through a selected named config', () => {
+ expect(() =>
+ assertAgentAttachmentLimits({
+ attachments: [{ file_id: 'one' }, { file_id: 'two' }],
+ req: {
+ config: {
+ fileConfig: {
+ endpoints: {
+ Moonshot: { supportedMimeTypes: ['^text/plain$'] },
+ custom: { fileLimit: 10 },
+ default: { fileLimit: 1 },
+ },
+ },
+ },
+ },
+ endpoint: 'Moonshot',
+ }),
+ ).toThrow(expect.objectContaining({ limitType: 'count', observed: 2, limit: 1 }));
+ });
+
+ it('prefers an exact custom endpoint key over a colliding normalized key', () => {
+ expect(() =>
+ assertAgentAttachmentLimits({
+ attachments: [{ file_id: 'one' }, { file_id: 'two' }],
+ req: {
+ config: {
+ fileConfig: {
+ endpoints: {
+ 'foo-bar': { fileLimit: 1 },
+ foobar: { fileLimit: 2 },
+ },
+ },
+ },
+ },
+ endpoint: 'foobar',
+ }),
+ ).not.toThrow();
+ });
+
+ it('preserves an explicit backing-endpoint aggregate override', () => {
+ expect(() =>
+ assertAgentAttachmentLimits({
+ attachments: [{ file_id: 'large', bytes: 200 * 1024 * 1024 }],
+ req: {
+ config: { fileConfig: { endpoints: { openAI: { totalSizeLimit: 256 } } } },
+ },
+ endpoint: EModelEndpoint.openAI,
+ }),
+ ).not.toThrow();
+ });
+
+ it('falls back to the agents aggregate limit for a provider-backed agent', () => {
+ expect(() =>
+ assertAgentAttachmentLimits({
+ attachments: [{ file_id: 'large', bytes: 21 * 1024 * 1024 }],
+ req: {
+ config: { fileConfig: { endpoints: { agents: { totalSizeLimit: 20 } } } },
+ },
+ endpoint: EModelEndpoint.openAI,
+ }),
+ ).toThrow(expect.objectContaining({ limitType: 'bytes', limit: 20 * 1024 * 1024 }));
+ });
+
+ it('honors the generic custom-endpoint aggregate fallback', () => {
+ expect(() =>
+ assertAgentAttachmentLimits({
+ attachments: [{ file_id: 'custom-file', bytes: 2 * 1024 * 1024 }],
+ req: {
+ config: { fileConfig: { endpoints: { custom: { totalSizeLimit: 1 } } } },
+ },
+ endpoint: 'Named Compatible Provider',
+ }),
+ ).toThrow(expect.objectContaining({ limitType: 'bytes', limit: 1024 * 1024 }));
+ });
+
+ it('does not borrow an agents aggregate limit through a selected partial custom config', () => {
+ expect(() =>
+ assertAgentAttachmentLimits({
+ attachments: [{ file_id: 'custom-file', bytes: 200 * 1024 * 1024 }],
+ req: {
+ config: {
+ fileConfig: {
+ endpoints: {
+ agents: { totalSizeLimit: 256 },
+ custom: { fileLimit: 5 },
+ },
+ },
+ },
+ },
+ endpoint: 'Named Compatible Provider',
+ }),
+ ).toThrow(expect.objectContaining({ limitType: 'bytes', limit: 128 * 1024 * 1024 }));
+ });
+
+ it('honors the explicitly configured default aggregate fallback', () => {
+ expect(() =>
+ assertAgentAttachmentLimits({
+ attachments: [{ file_id: 'default-file', bytes: 2 * 1024 * 1024 }],
+ req: {
+ config: { fileConfig: { endpoints: { default: { totalSizeLimit: 1 } } } },
+ },
+ endpoint: EModelEndpoint.openAI,
+ }),
+ ).toThrow(expect.objectContaining({ limitType: 'bytes', limit: 1024 * 1024 }));
+ });
+
+ it('logs memory snapshots around model execution when attachments are present', () => {
+ const loggerInfo = logger.info as jest.Mock;
+ loggerInfo.mockClear();
+ const callback = createAgentMemoryCallback({
+ conversationId: 'conversation-1',
+ messageId: 'message-1',
+ attachments: [makeTextFile('file-1', 'file.txt', 'context')],
+ });
+
+ callback.handleChatModelStart(undefined, [], 'run-1');
+ callback.handleLLMEnd({}, 'run-1');
+
+ expect(loggerInfo.mock.calls.map(([, fields]) => fields.phase)).toEqual([
+ 'before_model',
+ 'after_model',
+ ]);
+ expect(loggerInfo).toHaveBeenLastCalledWith(
+ '[AgentAttachmentMemory] snapshot',
+ expect.objectContaining({
+ modelRunId: 'run-1',
+ attachmentCount: 1,
+ extractedTextChars: 7,
+ rss: expect.any(Number),
+ heapUsed: expect.any(Number),
+ external: expect.any(Number),
+ arrayBuffers: expect.any(Number),
+ }),
+ );
+ });
+
+ it('does not log attachment snapshots for runs without attachments', () => {
+ const loggerInfo = logger.info as jest.Mock;
+ loggerInfo.mockClear();
+ const callback = createAgentMemoryCallback({ attachments: [] });
+
+ callback.handleChatModelStart(undefined, [], 'run-1');
+ callback.handleLLMEnd({}, 'run-1');
+
+ expect(loggerInfo).not.toHaveBeenCalled();
+ });
+
+ it('counts repeated binary bytes in memory snapshots', () => {
+ const loggerInfo = logger.info as jest.Mock;
+ loggerInfo.mockClear();
+ const repeated = {
+ file_id: 'replayed-pdf',
+ bytes: 70 * 1024 * 1024,
+ type: 'application/pdf',
+ } as IMongoFile;
+ const callback = createAgentMemoryCallback({
+ attachments: [repeated, repeated],
+ countRepeatedExtractedText: true,
+ });
+
+ callback.handleChatModelStart(undefined, [], 'run-replay');
+
+ expect(loggerInfo).toHaveBeenCalledWith(
+ '[AgentAttachmentMemory] snapshot',
+ expect.objectContaining({ totalKnownBytes: 140 * 1024 * 1024 }),
+ );
+ });
+
it('collects file ids from attachment-like files', () => {
const fileIds = collectFileIds([
{ file_id: 'file-1' },
@@ -77,7 +428,7 @@ describe('agent attachment helpers', () => {
const req = {
body: { fileTokenLimit: 1000 },
config: {},
- } as ServerRequest;
+ } as unknown as ServerRequest;
const scopedContext = await buildAgentScopedContext({
agentIds: ['agent-a', 'agent-b'],
@@ -94,4 +445,206 @@ describe('agent attachment helpers', () => {
expect(scopedContext.get('agent-a')).not.toContain('Shared duplicate context');
expect(scopedContext.has('agent-b')).toBe(false);
});
+
+ it('counts repeated extracted context once per agent injection', async () => {
+ const repeatedContext = makeTextFile('shared-context', 'shared.txt', 'x'.repeat(600_000));
+ const req = {
+ body: { fileTokenLimit: 1_000_000 },
+ config: { fileConfig: { fileContextCharLimit: 1_000_000 } },
+ } as ServerRequest;
+
+ await expect(
+ buildAgentScopedContext({
+ agentIds: ['agent-a', 'agent-b'],
+ attachmentsByAgentId: new Map([
+ ['agent-a', [repeatedContext]],
+ ['agent-b', [repeatedContext]],
+ ]),
+ req,
+ }),
+ ).rejects.toMatchObject({
+ code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED',
+ limitType: 'extracted_text',
+ observed: 1_200_000,
+ });
+ });
+
+ it('applies each agent backing endpoint limit before scoped extraction', async () => {
+ const oversized = {
+ ...makeTextFile('moonshot-file', 'moonshot.txt', 'context'),
+ bytes: 2 * 1024 * 1024,
+ };
+ const req = {
+ body: { fileTokenLimit: 1000 },
+ config: {
+ fileConfig: { endpoints: { Moonshot: { fileLimit: 10, totalSizeLimit: 1 } } },
+ },
+ } as unknown as ServerRequest;
+
+ await expect(
+ buildAgentScopedContext({
+ agentIds: ['primary', 'secondary'],
+ attachmentsByAgentId: new Map([['secondary', [oversized]]]),
+ endpointsByAgentId: new Map([
+ ['primary', { endpoint: 'openAI' }],
+ ['secondary', { endpoint: 'Moonshot' }],
+ ]),
+ req,
+ }),
+ ).rejects.toMatchObject({
+ code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED',
+ limitType: 'bytes',
+ });
+ });
+
+ it('applies each agent backing endpoint limit to shared attachments', async () => {
+ const sharedAttachments = [
+ makeTextFile('shared-1', 'shared-1.txt', 'one'),
+ makeTextFile('shared-2', 'shared-2.txt', 'two'),
+ ];
+ const req = {
+ body: { fileTokenLimit: 1000 },
+ config: {
+ fileConfig: {
+ endpoints: { openAI: { fileLimit: 10 }, Moonshot: { fileLimit: 1 } },
+ },
+ },
+ } as unknown as ServerRequest;
+
+ await expect(
+ buildAgentScopedContext({
+ agentIds: ['primary', 'secondary'],
+ attachmentsByAgentId: new Map(),
+ sharedAttachments,
+ sharedRunAttachmentIds: new Set(sharedAttachments.map(({ file_id }) => file_id)),
+ endpointsByAgentId: new Map([
+ ['primary', { endpoint: 'openAI' }],
+ ['secondary', { endpoint: 'Moonshot' }],
+ ]),
+ req,
+ }),
+ ).rejects.toMatchObject({
+ code: 'AGENT_ATTACHMENT_LIMIT_EXCEEDED',
+ limitType: 'count',
+ observed: 2,
+ limit: 1,
+ });
+ });
+
+ it('rejects shared attachments incompatible with a receiving agent', async () => {
+ const sharedAttachment = {
+ ...makeTextFile('shared-pdf', 'shared.pdf', ''),
+ source: FileSources.local,
+ type: 'application/pdf',
+ bytes: 1,
+ };
+ const req = {
+ body: { fileTokenLimit: 1000 },
+ config: {
+ fileConfig: {
+ endpoints: { Moonshot: { fileLimit: 10, supportedMimeTypes: ['^text/plain$'] } },
+ },
+ },
+ } as unknown as ServerRequest;
+
+ await expect(
+ buildAgentScopedContext({
+ agentIds: ['secondary'],
+ attachmentsByAgentId: new Map(),
+ sharedAttachments: [sharedAttachment],
+ endpointsByAgentId: new Map([['secondary', { endpoint: 'Moonshot' }]]),
+ req,
+ }),
+ ).rejects.toBeInstanceOf(AgentAttachmentPolicyError);
+ });
+
+ it('does not apply the primary file count limit across disjoint private scopes', async () => {
+ const req = {
+ body: { fileTokenLimit: 1000 },
+ config: {
+ fileConfig: {
+ endpoints: { openAI: { fileLimit: 1 }, Moonshot: { fileLimit: 10 } },
+ },
+ },
+ } as unknown as ServerRequest;
+
+ await expect(
+ buildAgentScopedContext({
+ agentIds: ['primary', 'secondary'],
+ attachmentsByAgentId: new Map([
+ [
+ 'secondary',
+ [
+ makeTextFile('secondary-1', 'secondary-1.txt', 'one'),
+ makeTextFile('secondary-2', 'secondary-2.txt', 'two'),
+ ],
+ ],
+ ]),
+ endpointsByAgentId: new Map([
+ ['primary', { endpoint: 'openAI' }],
+ ['secondary', { endpoint: 'Moonshot' }],
+ ]),
+ req,
+ }),
+ ).resolves.toEqual(new Map([['secondary', expect.stringContaining('secondary-1.txt')]]));
+ });
+
+ it('uses the global byte cap across disjoint private scopes', async () => {
+ const secondaryContext = {
+ ...makeTextFile('secondary-large', 'secondary-large.txt', 'context'),
+ bytes: 2 * 1024 * 1024,
+ };
+ const req = {
+ body: { fileTokenLimit: 1000 },
+ config: {
+ fileConfig: {
+ endpoints: {
+ openAI: { fileLimit: 10, totalSizeLimit: 1 },
+ Moonshot: { fileLimit: 10, totalSizeLimit: 10 },
+ },
+ },
+ },
+ } as unknown as ServerRequest;
+
+ await expect(
+ buildAgentScopedContext({
+ agentIds: ['primary', 'secondary'],
+ attachmentsByAgentId: new Map([['secondary', [secondaryContext]]]),
+ endpointsByAgentId: new Map([
+ ['primary', { endpoint: 'openAI' }],
+ ['secondary', { endpoint: 'Moonshot' }],
+ ]),
+ endpoint: 'openAI',
+ req,
+ }),
+ ).resolves.toEqual(new Map([['secondary', expect.stringContaining('secondary-large.txt')]]));
+ });
+
+ it('filters endpoint-incompatible scoped resources before admission', async () => {
+ const unsupported = Array.from({ length: 11 }, (_, index) => ({
+ ...makeTextFile(`binary-${index}`, `binary-${index}.bin`, ''),
+ source: FileSources.local,
+ type: 'application/octet-stream',
+ bytes: 1,
+ }));
+ const req = {
+ body: { fileTokenLimit: 1000 },
+ config: {
+ fileConfig: {
+ endpoints: { Moonshot: { fileLimit: 10, supportedMimeTypes: ['^text/plain$'] } },
+ },
+ },
+ } as unknown as ServerRequest;
+
+ await expect(
+ buildAgentScopedContext({
+ agentIds: ['secondary'],
+ attachmentsByAgentId: new Map([['secondary', unsupported]]),
+ endpointsByAgentId: new Map([
+ ['secondary', { endpoint: 'Moonshot', endpointType: EModelEndpoint.custom }],
+ ]),
+ req,
+ }),
+ ).resolves.toEqual(new Map());
+ });
});
diff --git a/packages/api/src/agents/attachments.ts b/packages/api/src/agents/attachments.ts
index 4065757af1..438e58fd78 100644
--- a/packages/api/src/agents/attachments.ts
+++ b/packages/api/src/agents/attachments.ts
@@ -1,6 +1,15 @@
+import { logger } from '@librechat/data-schemas';
+import {
+ EModelEndpoint,
+ FileSources,
+ getEndpointFileConfig,
+ mergeFileConfig,
+} from 'librechat-data-provider';
import type { IMongoFile } from '@librechat/data-schemas';
import type { TokenCountFn } from '~/utils/text';
import type { ServerRequest } from '~/types';
+import { filterFilesByEndpointRuntimeConfig } from '~/files/filter';
+import { AGENT_ATTACHMENT_LIMIT_EXCEEDED } from './errors';
import { countTokens } from '~/utils/tokenizer';
import { extractFileContext } from '~/files';
@@ -8,6 +17,455 @@ type FileWithId = {
file_id?: string | null;
};
+type AttachmentTelemetryFile = FileWithId & {
+ bytes?: number | null;
+ source?: string | null;
+ type?: string | null;
+ text?: string | null;
+ metadata?: (IMongoFile['metadata'] & { pageCount?: number | null }) | null;
+};
+
+/** Whether a hydrated file contributes content to the model prompt itself. */
+export function isModelBoundAttachmentFile(
+ file: AttachmentTelemetryFile | null | undefined,
+): boolean {
+ if (!file) {
+ return false;
+ }
+ const source = file.source ?? FileSources.local;
+ if (source === FileSources.text) {
+ return typeof file.text === 'string' && file.text.length > 0;
+ }
+ const metadata = file.metadata as
+ | (IMongoFile['metadata'] & { fileIdentifier?: unknown })
+ | null
+ | undefined;
+ return !(
+ (file as IMongoFile).embedded === true ||
+ metadata?.codeEnvRef != null ||
+ metadata?.codeEnvRefs != null ||
+ metadata?.fileIdentifier != null
+ );
+}
+
+type AgentAttachmentLimitRequest = {
+ config?: {
+ fileConfig?: Parameters<typeof mergeFileConfig>[0];
+ };
+};
+
+type DynamicFileConfig = Parameters<typeof mergeFileConfig>[0];
+type EndpointFileConfigs = NonNullable<NonNullable<DynamicFileConfig>['endpoints']>;
+
+function normalizeEndpointConfigKey(value: string | null | undefined): string {
+ const name = value ?? '';
+ return name.toLowerCase() === 'ollama' ? 'ollama' : name;
+}
+
+function findEndpointConfig(endpoints: EndpointFileConfigs, candidate: string | null | undefined) {
+ if (!candidate) {
+ return undefined;
+ }
+ if (Object.prototype.hasOwnProperty.call(endpoints, candidate)) {
+ return endpoints[candidate];
+ }
+ const normalizedCandidate = normalizeEndpointConfigKey(candidate);
+ return Object.entries(endpoints).find(
+ ([key]) => normalizeEndpointConfigKey(key) === normalizedCandidate,
+ )?.[1];
+}
+
+function getExplicitEndpointAggregateLimit(
+ fileConfig: Parameters<typeof mergeFileConfig>[0],
+ endpoint: string | null | undefined,
+ endpointType: string | null | undefined,
+): number | undefined {
+ const endpoints = fileConfig?.endpoints ?? {};
+ const normalizedEndpoint = normalizeEndpointConfigKey(endpoint);
+ const standardEndpoints = new Set(
+ [
+ EModelEndpoint.agents,
+ EModelEndpoint.assistants,
+ EModelEndpoint.azureAssistants,
+ EModelEndpoint.openAI,
+ EModelEndpoint.azureOpenAI,
+ EModelEndpoint.anthropic,
+ EModelEndpoint.google,
+ EModelEndpoint.bedrock,
+ ].map(normalizeEndpointConfigKey),
+ );
+ const isCustomEndpoint =
+ endpointType === EModelEndpoint.custom ||
+ (normalizedEndpoint.length > 0 && !standardEndpoints.has(normalizedEndpoint));
+ let selectedConfig;
+ if (isCustomEndpoint) {
+ selectedConfig =
+ findEndpointConfig(endpoints, endpoint) ??
+ findEndpointConfig(endpoints, EModelEndpoint.custom) ??
+ findEndpointConfig(endpoints, EModelEndpoint.agents);
+ } else {
+ selectedConfig =
+ findEndpointConfig(endpoints, endpointType) ?? findEndpointConfig(endpoints, endpoint);
+ if (selectedConfig?.totalSizeLimit === undefined) {
+ selectedConfig = findEndpointConfig(endpoints, EModelEndpoint.agents) ?? selectedConfig;
+ }
+ }
+ const configuredLimit = selectedConfig?.totalSizeLimit ?? endpoints.default?.totalSizeLimit;
+ return configuredLimit === undefined ? undefined : configuredLimit * 1024 * 1024;
+}
+
+function getExplicitEndpointFileLimit(
+ fileConfig: Parameters<typeof mergeFileConfig>[0],
+ endpoint: string | null | undefined,
+ endpointType: string | null | undefined,
+ fallbackLimit: number | undefined,
+): number | undefined {
+ const endpoints = fileConfig?.endpoints ?? {};
+ const resolveSelectedLimit = (config: ReturnType<typeof findEndpointConfig>) =>
+ config == null
+ ? undefined
+ : (config.fileLimit ?? endpoints.default?.fileLimit ?? fallbackLimit);
+ const normalizedEndpoint = normalizeEndpointConfigKey(endpoint);
+ const standardEndpoints = new Set(
+ [
+ EModelEndpoint.agents,
+ EModelEndpoint.assistants,
+ EModelEndpoint.azureAssistants,
+ EModelEndpoint.openAI,
+ EModelEndpoint.azureOpenAI,
+ EModelEndpoint.anthropic,
+ EModelEndpoint.google,
+ EModelEndpoint.bedrock,
+ ].map(normalizeEndpointConfigKey),
+ );
+ const isCustomEndpoint =
+ endpointType === EModelEndpoint.custom ||
+ (normalizedEndpoint.length > 0 && !standardEndpoints.has(normalizedEndpoint));
+ if (isCustomEndpoint) {
+ const namedConfig = findEndpointConfig(endpoints, endpoint);
+ if (namedConfig) {
+ return resolveSelectedLimit(namedConfig);
+ }
+ return resolveSelectedLimit(findEndpointConfig(endpoints, EModelEndpoint.custom));
+ }
+ return (
+ findEndpointConfig(endpoints, endpointType)?.fileLimit ??
+ findEndpointConfig(endpoints, endpoint)?.fileLimit
+ );
+}
+
+export type AgentAttachmentLimit = 'count' | 'bytes' | 'extracted_text';
+
+export interface AgentAttachmentStats {
+ attachmentCount: number;
+ totalKnownBytes: number;
+ extractedTextChars: number;
+ files: Array<{
+ fileId?: string;
+ mimeType?: string;
+ bytes?: number;
+ extractedTextChars?: number;
+ pageCount?: number;
+ }>;
+}
+
+export class AgentAttachmentLimitError extends Error {
+ readonly code: typeof AGENT_ATTACHMENT_LIMIT_EXCEEDED = AGENT_ATTACHMENT_LIMIT_EXCEEDED;
+ readonly status = 413;
+ readonly statusCode = 413;
+
+ constructor(
+ readonly limitType: AgentAttachmentLimit,
+ readonly observed: number,
+ readonly limit: number,
+ ) {
+ const labels: Record<AgentAttachmentLimit, string> = {
+ count: 'attachment count',
+ bytes: 'total attachment size',
+ extracted_text: 'extracted document text',
+ };
+ super(
+ `This turn exceeds the configured ${labels[limitType]} limit (${observed} > ${limit}). Remove some attachments or use smaller files and try again.`,
+ );
+ this.name = 'AgentAttachmentLimitError';
+ }
+}
+
+export class AgentAttachmentPolicyError extends Error {
+ readonly code: typeof AGENT_ATTACHMENT_LIMIT_EXCEEDED = AGENT_ATTACHMENT_LIMIT_EXCEEDED;
+ readonly status = 413;
+ readonly statusCode = 413;
+
+ constructor() {
+ super(
+ 'An attachment is not supported by every agent in this run. Remove it or use compatible agents and try again.',
+ );
+ this.name = 'AgentAttachmentPolicyError';
+ }
+}
+
+export function isAgentAttachmentLimitError(
+ error: unknown,
+): error is AgentAttachmentLimitError | AgentAttachmentPolicyError {
+ return error instanceof AgentAttachmentLimitError || error instanceof AgentAttachmentPolicyError;
+}
+
+export function collectAgentAttachmentStats(
+ attachments?: Iterable<AttachmentTelemetryFile | null | undefined> | null,
+ options: { countRepeatedExtractedText?: boolean; countRepeatedBytes?: boolean } = {},
+): AgentAttachmentStats {
+ const stats: AgentAttachmentStats = {
+ attachmentCount: 0,
+ totalKnownBytes: 0,
+ extractedTextChars: 0,
+ files: [],
+ };
+ const seenFileIds = new Set<string>();
+
+ for (const file of attachments ?? []) {
+ if (!file) {
+ continue;
+ }
+ const extractedTextChars = typeof file.text === 'string' ? file.text.length : 0;
+ if (file.file_id && seenFileIds.has(file.file_id)) {
+ if (options.countRepeatedExtractedText === true) {
+ stats.extractedTextChars += extractedTextChars;
+ }
+ if (options.countRepeatedBytes === true) {
+ stats.totalKnownBytes +=
+ Number.isFinite(file.bytes) && Number(file.bytes) >= 0 ? Number(file.bytes) : 0;
+ }
+ continue;
+ }
+ if (file.file_id) {
+ seenFileIds.add(file.file_id);
+ }
+
+ const bytes = Number.isFinite(file.bytes) && Number(file.bytes) >= 0 ? Number(file.bytes) : 0;
+ const pageCount =
+ Number.isFinite(file.metadata?.pageCount) && Number(file.metadata?.pageCount) >= 0
+ ? Number(file.metadata?.pageCount)
+ : undefined;
+ stats.attachmentCount += 1;
+ stats.totalKnownBytes += bytes;
+ stats.extractedTextChars += extractedTextChars;
+ stats.files.push({
+ ...(file.file_id && { fileId: file.file_id }),
+ ...(file.type && { mimeType: file.type }),
+ ...(bytes > 0 && { bytes }),
+ ...(extractedTextChars > 0 && { extractedTextChars }),
+ ...(pageCount != null && { pageCount }),
+ });
+ }
+
+ return stats;
+}
+
+export function assertAgentAttachmentLimits({
+ attachments,
+ req,
+ fileConfig: providedFileConfig,
+ endpoint = EModelEndpoint.agents,
+ endpointType,
+ countRepeatedExtractedText = false,
+ countRepeatedBytes = countRepeatedExtractedText,
+ enforceAttachmentCount = true,
+ useGlobalContextSizeLimit = false,
+}: {
+ attachments?: Iterable<AttachmentTelemetryFile | null | undefined> | null;
+ req?: AgentAttachmentLimitRequest;
+ fileConfig?: Parameters<typeof mergeFileConfig>[0];
+ endpoint?: string | null;
+ endpointType?: string | null;
+ countRepeatedExtractedText?: boolean;
+ countRepeatedBytes?: boolean;
+ enforceAttachmentCount?: boolean;
+ useGlobalContextSizeLimit?: boolean;
+}): AgentAttachmentStats {
+ const stats = collectAgentAttachmentStats(attachments, {
+ countRepeatedExtractedText,
+ countRepeatedBytes,
+ });
+ const dynamicFileConfig = providedFileConfig ?? req?.config?.fileConfig;
+ const fileConfig = mergeFileConfig(dynamicFileConfig);
+ const endpointConfig = getEndpointFileConfig({ fileConfig, endpoint, endpointType });
+ const configuredFileLimit =
+ getExplicitEndpointFileLimit(
+ dynamicFileConfig,
+ endpoint,
+ endpointType,
+ endpointConfig.fileLimit,
+ ) ??
+ dynamicFileConfig?.endpoints?.[EModelEndpoint.agents]?.fileLimit ??
+ endpointConfig.fileLimit;
+ const configuredContextSizeLimit =
+ (useGlobalContextSizeLimit
+ ? undefined
+ : getExplicitEndpointAggregateLimit(dynamicFileConfig, endpoint, endpointType)) ??
+ fileConfig.fileContextSizeLimit;
+ const configuredContextCharLimit = dynamicFileConfig?.fileContextCharLimit;
+ const limits: Array<[AgentAttachmentLimit, number, number | undefined]> = [
+ ['count', stats.attachmentCount, enforceAttachmentCount ? configuredFileLimit : undefined],
+ ['bytes', stats.totalKnownBytes, configuredContextSizeLimit],
+ [
+ 'extracted_text',
+ stats.extractedTextChars,
+ configuredContextCharLimit ?? fileConfig.fileContextCharLimit,
+ ],
+ ];
+
+ for (const [limitType, observed, limit] of limits) {
+ if (limit != null && limit > 0 && observed > limit) {
+ throw new AgentAttachmentLimitError(limitType, observed, limit);
+ }
+ }
+
+ return stats;
+}
+
+export function assertAgentAttachmentTopology({
+ sharedAttachments = [],
+ scopedAttachmentsByAgentId = new Map(),
+ req,
+ endpoint,
+ endpointType,
+ endpointsByAgentId,
+}: {
+ sharedAttachments?: IMongoFile[];
+ scopedAttachmentsByAgentId?: Map<string, IMongoFile[]>;
+ req?: ServerRequest;
+ endpoint?: string | null;
+ endpointType?: string | null;
+ endpointsByAgentId?: AgentAttachmentEndpointsByAgentId;
+}): void {
+ const agentIds = new Set([
+ ...scopedAttachmentsByAgentId.keys(),
+ ...(endpointsByAgentId instanceof Map
+ ? endpointsByAgentId.keys()
+ : Object.keys(endpointsByAgentId ?? {})),
+ ]);
+ for (const agentId of agentIds) {
+ const agentEndpoint =
+ endpointsByAgentId instanceof Map
+ ? endpointsByAgentId.get(agentId)
+ : endpointsByAgentId?.[agentId];
+ const compatibleSharedAttachments = filterFilesByEndpointRuntimeConfig(req?.config, {
+ files: sharedAttachments,
+ endpoint: agentEndpoint?.endpoint ?? endpoint ?? EModelEndpoint.agents,
+ endpointType: agentEndpoint?.endpointType ?? endpointType,
+ skipTotalSizeLimit: true,
+ preserveTextSources: true,
+ });
+ if (compatibleSharedAttachments.length !== sharedAttachments.length) {
+ throw new AgentAttachmentPolicyError();
+ }
+ assertAgentAttachmentLimits({
+ attachments: [
+ ...compatibleSharedAttachments,
+ ...(scopedAttachmentsByAgentId.get(agentId) ?? []),
+ ],
+ req,
+ endpoint: agentEndpoint?.endpoint,
+ endpointType: agentEndpoint?.endpointType,
+ countRepeatedExtractedText: true,
+ });
+ }
+ assertAgentAttachmentLimits({
+ attachments: [...scopedAttachmentsByAgentId.values()].flat(),
+ req,
+ endpoint,
+ endpointType,
+ countRepeatedExtractedText: true,
+ enforceAttachmentCount: false,
+ useGlobalContextSizeLimit: true,
+ });
+}
+
+type AgentMemoryPhase =
+ | 'before_process_attachments'
+ | 'after_process_attachments'
+ | 'before_encode_documents'
+ | 'after_encode_documents'
+ | 'before_context_assembly'
+ | 'after_context_assembly'
+ | 'before_model'
+ | 'after_model'
+ | 'model_error'
+ | 'before_terminal_save'
+ | 'after_terminal_save'
+ | 'before_final_publish'
+ | 'after_final_publish';
+
+interface AgentMemoryContext {
+ req?: ServerRequest;
+ conversationId?: string | null;
+ messageId?: string | null;
+ attachments?: Iterable<AttachmentTelemetryFile | null | undefined> | null;
+ countRepeatedExtractedText?: boolean;
+}
+
+export function logAgentMemorySnapshot(
+ phase: AgentMemoryPhase,
+ context: AgentMemoryContext,
+ modelRunId?: string,
+): void {
+ const attachments = collectAgentAttachmentStats(context.attachments, {
+ countRepeatedExtractedText: context.countRepeatedExtractedText,
+ countRepeatedBytes: context.countRepeatedExtractedText,
+ });
+ if (attachments.attachmentCount === 0) {
+ return;
+ }
+ const memory = process.memoryUsage();
+ logger.info('[AgentAttachmentMemory] snapshot', {
+ phase,
+ rss: memory.rss,
+ heapUsed: memory.heapUsed,
+ external: memory.external,
+ arrayBuffers: memory.arrayBuffers ?? 0,
+ conversationId: context.conversationId,
+ messageId: context.messageId,
+ jobId: (context.req as (ServerRequest & { _resumableStreamId?: string }) | undefined)
+ ?._resumableStreamId,
+ userId: context.req?.user?.id,
+ tenantId: context.req?.user?.tenantId,
+ modelRunId,
+ ...attachments,
+ });
+}
+
+export function createAgentMemoryCallback(context: AgentMemoryContext): {
+ name: string;
+ handleChatModelStart: (...args: unknown[]) => void;
+ handleLLMStart: (...args: unknown[]) => void;
+ handleLLMEnd: (_output: unknown, runId: string) => void;
+ handleLLMError: (_error: unknown, runId: string) => void;
+} {
+ const startedRuns = new Set<string>();
+ const logStart = (...args: unknown[]): void => {
+ const runId = typeof args[2] === 'string' ? args[2] : undefined;
+ if (runId && startedRuns.has(runId)) {
+ return;
+ }
+ if (runId) {
+ startedRuns.add(runId);
+ }
+ logAgentMemorySnapshot('before_model', context, runId);
+ };
+ const logEnd = (phase: 'after_model' | 'model_error', runId: string): void => {
+ startedRuns.delete(runId);
+ logAgentMemorySnapshot(phase, context, runId);
+ };
+
+ return {
+ name: 'librechat-agent-attachment-memory',
+ handleChatModelStart: logStart,
+ handleLLMStart: logStart,
+ handleLLMEnd: (_output, runId) => logEnd('after_model', runId),
+ handleLLMError: (_error, runId) => logEnd('model_error', runId),
+ };
+}
+
export type AgentContextAttachmentCarrier<TFile extends FileWithId = IMongoFile> = {
id?: string | null;
agentContextAttachments?: TFile[] | null;
@@ -23,6 +481,10 @@ export type AgentContextAttachmentsByAgentId<TFile extends FileWithId = IMongoFi
| null
| undefined;
+export type AgentAttachmentEndpointsByAgentId =
+ | Map<string, { endpoint?: string | null; endpointType?: string | null }>
+ | Record<string, { endpoint?: string | null; endpointType?: string | null }>;
+
export function collectFileIds<TFile extends FileWithId>(
files?: Array<TFile | null | undefined> | null,
): Set<string> {
@@ -85,27 +547,89 @@ export function getAgentContextAttachments<TFile extends FileWithId>({
return attachments.filter((file) => !file?.file_id || !excludeFileIds.has(file.file_id));
}
+export function buildAgentScopedAttachmentMap({
+ agentIds,
+ attachmentsByAgentId,
+ sharedRunAttachmentIds,
+ req,
+ endpoint,
+ endpointType,
+ endpointsByAgentId,
+}: {
+ agentIds: string[];
+ attachmentsByAgentId: AgentContextAttachmentsByAgentId<IMongoFile>;
+ sharedRunAttachmentIds?: Set<string>;
+ req?: ServerRequest;
+ endpoint?: string | null;
+ endpointType?: string | null;
+ endpointsByAgentId?: AgentAttachmentEndpointsByAgentId;
+}): Map<string, IMongoFile[]> {
+ const entries = Array.from(new Set(agentIds.filter(Boolean))).map((agentId) => {
+ const agentEndpoint =
+ endpointsByAgentId instanceof Map
+ ? endpointsByAgentId.get(agentId)
+ : endpointsByAgentId?.[agentId];
+ const attachments = getAgentContextAttachments({
+ agentId,
+ attachmentsByAgentId,
+ excludeFileIds: sharedRunAttachmentIds,
+ }).filter(isModelBoundAttachmentFile);
+ return [
+ agentId,
+ filterFilesByEndpointRuntimeConfig(req?.config, {
+ files: attachments,
+ endpoint: agentEndpoint?.endpoint ?? endpoint ?? EModelEndpoint.agents,
+ endpointType: agentEndpoint?.endpointType ?? endpointType,
+ skipTotalSizeLimit: true,
+ preserveTextSources: true,
+ }),
+ ] as const;
+ });
+ return new Map(entries);
+}
+
export async function buildAgentScopedContext({
agentIds,
attachmentsByAgentId,
sharedRunAttachmentIds,
+ sharedAttachments = [],
req,
tokenCountFn = countTokens,
+ endpoint,
+ endpointType,
+ endpointsByAgentId,
}: {
agentIds: string[];
attachmentsByAgentId: AgentContextAttachmentsByAgentId<IMongoFile>;
sharedRunAttachmentIds?: Set<string>;
+ sharedAttachments?: IMongoFile[];
req?: ServerRequest;
tokenCountFn?: TokenCountFn;
+ endpoint?: string | null;
+ endpointType?: string | null;
+ endpointsByAgentId?: AgentAttachmentEndpointsByAgentId;
}): Promise<Map<string, string>> {
- const uniqueAgentIds = Array.from(new Set(agentIds.filter(Boolean)));
+ const attachmentEntries = [
+ ...buildAgentScopedAttachmentMap({
+ agentIds,
+ attachmentsByAgentId,
+ sharedRunAttachmentIds,
+ req,
+ endpoint,
+ endpointType,
+ endpointsByAgentId,
+ }),
+ ];
+ assertAgentAttachmentTopology({
+ sharedAttachments,
+ scopedAttachmentsByAgentId: new Map(attachmentEntries),
+ req,
+ endpoint,
+ endpointType,
+ endpointsByAgentId,
+ });
const entries = await Promise.all(
- uniqueAgentIds.map(async (agentId) => {
- const attachments = getAgentContextAttachments({
- agentId,
- attachmentsByAgentId,
- excludeFileIds: sharedRunAttachmentIds,
- });
+ attachmentEntries.map(async ([agentId, attachments]) => {
if (attachments.length === 0) {
return [agentId, ''] as const;
}
diff --git a/packages/api/src/agents/errors.spec.ts b/packages/api/src/agents/errors.spec.ts
index 866236e9ef..9c1130d4fa 100644
--- a/packages/api/src/agents/errors.spec.ts
+++ b/packages/api/src/agents/errors.spec.ts
@@ -6,6 +6,7 @@ import {
resolveLangChainError,
getUserFacingProviderError,
isFatalAgentInitializationError,
+ AGENT_ATTACHMENT_LIMIT_EXCEEDED,
AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE,
isStepLimitError,
} from './errors';
@@ -14,6 +15,7 @@ describe('isFatalAgentInitializationError', () => {
it.each([
ErrorTypes.RESOURCE_RECOVERY_REQUIRED,
ErrorTypes.STATEFUL_CODE_ENVIRONMENT_NOT_ALLOWED,
+ AGENT_ATTACHMENT_LIMIT_EXCEEDED,
AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE,
])('classifies %s as fatal', (code) => {
expect(isFatalAgentInitializationError({ code })).toBe(true);
diff --git a/packages/api/src/agents/errors.ts b/packages/api/src/agents/errors.ts
index 9a98ca9894..d3b05d20fe 100644
--- a/packages/api/src/agents/errors.ts
+++ b/packages/api/src/agents/errors.ts
@@ -5,6 +5,7 @@ import {
} from 'librechat-data-provider';
export const AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE = 'AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE';
+export const AGENT_ATTACHMENT_LIMIT_EXCEEDED = 'AGENT_ATTACHMENT_LIMIT_EXCEEDED';
export function createStatefulCodeEnvironmentPolicyError(environment: string): Error {
return Object.assign(
@@ -45,6 +46,7 @@ export function isFatalAgentInitializationError(
): boolean {
const code = getErrorCode(error);
return (
+ code === AGENT_ATTACHMENT_LIMIT_EXCEEDED ||
code === ErrorTypes.RESOURCE_RECOVERY_REQUIRED ||
code === ErrorTypes.STATEFUL_CODE_ENVIRONMENT_NOT_ALLOWED ||
(code === AGENT_EXPECTED_MCP_TOOLS_UNAVAILABLE && options.allowExpectedMCPFallback !== true)
diff --git a/packages/api/src/agents/hitl/protection.spec.ts b/packages/api/src/agents/hitl/protection.spec.ts
index bb46e0d6f1..7b81490610 100644
--- a/packages/api/src/agents/hitl/protection.spec.ts
+++ b/packages/api/src/agents/hitl/protection.spec.ts
@@ -51,15 +51,278 @@ describe('assertResumeRuntimeContentAllowed', () => {
},
},
},
- ])('does not read checkpoints for unrelated or inert policy %#', async (appConfig) => {
+ ])(
+ 'reads only checkpoint state for unrelated or inert temporary policy %#',
+ async (appConfig) => {
+ const dependencies = createDependencies();
+
+ await expect(
+ assertResumeRuntimeContentAllowed(createInput(appConfig), dependencies),
+ ).resolves.toEqual({ resolvedFiles: [], checkpointFiles: [] });
+ expect(dependencies.getAgentCheckpointer).toHaveBeenCalledTimes(1);
+ expect(dependencies.getMessages).not.toHaveBeenCalled();
+ expect(dependencies.getFiles).not.toHaveBeenCalled();
+ },
+ );
+
+ it('hydrates checkpoint-bound files when content filters are inactive', async () => {
const dependencies = createDependencies();
+ dependencies.getAgentCheckpointer.mockResolvedValue({
+ getTuple: jest.fn().mockResolvedValue({
+ checkpoint: {
+ channel_values: {
+ messages: [
+ {
+ role: 'human',
+ additional_kwargs: { sourceMessageId: 'source-message' },
+ },
+ ],
+ },
+ },
+ }),
+ });
+ dependencies.getMessages.mockResolvedValue([
+ {
+ messageId: 'source-message',
+ files: [{ file_id: 'historical-file' }],
+ attachments: [{ file_id: 'display-only-file' }],
+ },
+ {
+ messageId: 'pre-summary-message',
+ files: [{ file_id: 'pre-summary-file' }],
+ },
+ ]);
+ dependencies.getFiles.mockResolvedValue([
+ {
+ file_id: 'historical-file',
+ filename: 'history.txt',
+ source: 'text',
+ type: 'text/plain',
+ text: 'historical context',
+ },
+ ]);
+ const input = { ...createInput({}), isTemporary: false };
- await expect(
- assertResumeRuntimeContentAllowed(createInput(appConfig), dependencies),
- ).resolves.toEqual({ resolvedFiles: [] });
- expect(dependencies.getAgentCheckpointer).not.toHaveBeenCalled();
+ await expect(assertResumeRuntimeContentAllowed(input, dependencies)).resolves.toEqual({
+ resolvedFiles: [],
+ checkpointFiles: [expect.objectContaining({ file_id: 'historical-file' })],
+ });
+ expect(dependencies.getMessages).toHaveBeenCalledWith({
+ conversationId: 'conversation-1',
+ user: 'user-1',
+ });
+ expect(dependencies.getFiles).toHaveBeenCalledWith(
+ { file_id: { $in: ['historical-file'] }, user: 'user-1' },
+ {},
+ {},
+ );
+ });
+
+ it('reuses supplied checkpoint source rows when content filters are inactive', async () => {
+ const dependencies = createDependencies();
+ dependencies.getAgentCheckpointer.mockResolvedValue({
+ getTuple: jest.fn().mockResolvedValue({
+ checkpoint: {
+ channel_values: {
+ messages: [
+ {
+ role: 'human',
+ additional_kwargs: { sourceMessageId: 'source-message' },
+ },
+ ],
+ },
+ },
+ }),
+ });
+ const resolvedFile = {
+ file_id: 'historical-file',
+ filename: 'history.txt',
+ source: 'text',
+ type: 'text/plain',
+ text: 'historical context',
+ };
+ dependencies.getFiles.mockResolvedValue([resolvedFile]);
+ const input = {
+ ...createInput({}),
+ isTemporary: false,
+ storedMessages: [
+ {
+ messageId: 'source-message',
+ files: [{ file_id: 'historical-file' }],
+ },
+ ],
+ };
+
+ await expect(assertResumeRuntimeContentAllowed(input, dependencies)).resolves.toEqual({
+ resolvedFiles: [],
+ checkpointFiles: [resolvedFile],
+ });
+ expect(dependencies.getMessages).not.toHaveBeenCalled();
+ expect(dependencies.getFiles).toHaveBeenCalledTimes(1);
+ });
+
+ it('hydrates files from every checkpoint source in plural lineage', async () => {
+ const dependencies = createDependencies();
+ dependencies.getAgentCheckpointer.mockResolvedValue({
+ getTuple: jest.fn().mockResolvedValue({
+ checkpoint: {
+ channel_values: {
+ messages: [
+ {
+ role: 'human',
+ additional_kwargs: { sourceMessageIds: ['source-one', 'source-two'] },
+ },
+ ],
+ },
+ },
+ }),
+ });
+ const resolvedFiles = [
+ { file_id: 'file-one', filename: 'one.txt', source: 'text', type: 'text/plain' },
+ { file_id: 'file-two', filename: 'two.txt', source: 'text', type: 'text/plain' },
+ ];
+ dependencies.getFiles.mockResolvedValue(resolvedFiles);
+ const input = {
+ ...createInput({}),
+ isTemporary: false,
+ storedMessages: [
+ { messageId: 'source-one', files: [{ file_id: 'file-one' }] },
+ { messageId: 'source-two', files: [{ file_id: 'file-two' }] },
+ ],
+ };
+
+ await expect(assertResumeRuntimeContentAllowed(input, dependencies)).resolves.toEqual({
+ resolvedFiles: [],
+ checkpointFiles: resolvedFiles,
+ });
expect(dependencies.getMessages).not.toHaveBeenCalled();
- expect(dependencies.getFiles).not.toHaveBeenCalled();
+ expect(dependencies.getFiles).toHaveBeenCalledWith(
+ { file_id: { $in: ['file-one', 'file-two'] }, user: 'user-1' },
+ {},
+ {},
+ );
+ });
+
+ it('hydrates files from user and tool checkpoint provenance lineage', async () => {
+ const dependencies = createDependencies();
+ dependencies.getAgentCheckpointer.mockResolvedValue({
+ getTuple: jest.fn().mockResolvedValue({
+ checkpoint: {
+ channel_values: {
+ messages: [
+ {
+ role: 'human',
+ additional_kwargs: {
+ provenance: {
+ parts: [
+ { attribution: 'user', sourceMessageId: 'source-user' },
+ { attribution: 'tool', sourceMessageId: 'source-tool' },
+ { attribution: 'synthetic', sourceMessageId: 'source-synthetic' },
+ ],
+ },
+ },
+ },
+ ],
+ },
+ },
+ }),
+ });
+ const resolvedFiles = [
+ { file_id: 'file-user', filename: 'user.txt', source: 'text', type: 'text/plain' },
+ { file_id: 'file-tool', filename: 'tool.txt', source: 'text', type: 'text/plain' },
+ ];
+ dependencies.getFiles.mockResolvedValue(resolvedFiles);
+ const input = {
+ ...createInput({}),
+ storedMessages: [
+ { messageId: 'source-user', files: [{ file_id: 'file-user' }] },
+ { messageId: 'source-tool', files: [{ file_id: 'file-tool' }] },
+ ],
+ };
+
+ await expect(assertResumeRuntimeContentAllowed(input, dependencies)).resolves.toEqual({
+ resolvedFiles: [],
+ checkpointFiles: resolvedFiles,
+ });
+ });
+
+ it('rejects a checkpoint source message that can no longer be loaded', async () => {
+ const dependencies = createDependencies();
+ dependencies.getAgentCheckpointer.mockResolvedValue({
+ getTuple: jest.fn().mockResolvedValue({
+ checkpoint: {
+ channel_values: {
+ messages: [
+ {
+ role: 'human',
+ additional_kwargs: { sourceMessageId: 'deleted-source' },
+ },
+ ],
+ },
+ },
+ }),
+ });
+ dependencies.getMessages.mockResolvedValue([]);
+
+ await expect(assertResumeRuntimeContentAllowed(createInput({}), dependencies)).rejects.toThrow(
+ 'checkpoint source message is no longer available',
+ );
+ });
+
+ it('preserves repeated steer file injections in checkpoint projection', async () => {
+ const dependencies = createDependencies();
+ dependencies.getAgentCheckpointer.mockResolvedValue({
+ getTuple: jest.fn().mockResolvedValue({
+ checkpoint: {
+ channel_values: {
+ messages: [
+ {
+ role: 'assistant',
+ content: [
+ { type: 'steer', files: [{ file_id: 'repeated-file' }] },
+ { type: 'steer', files: [{ file_id: 'repeated-file' }] },
+ ],
+ },
+ ],
+ },
+ },
+ }),
+ });
+ const resolvedFile = {
+ file_id: 'repeated-file',
+ filename: 'repeat.txt',
+ source: 'text',
+ type: 'text/plain',
+ text: 'repeated context',
+ };
+ dependencies.getFiles.mockResolvedValue([resolvedFile]);
+
+ await expect(assertResumeRuntimeContentAllowed(createInput({}), dependencies)).resolves.toEqual(
+ {
+ resolvedFiles: [],
+ checkpointFiles: [resolvedFile, resolvedFile],
+ },
+ );
+ });
+
+ it('rejects a checkpoint file reference that can no longer be hydrated', async () => {
+ const dependencies = createDependencies();
+ dependencies.getAgentCheckpointer.mockResolvedValue({
+ getTuple: jest.fn().mockResolvedValue({
+ checkpoint: {
+ channel_values: {
+ messages: [{ role: 'human', files: [{ file_id: 'deleted-file' }] }],
+ },
+ },
+ }),
+ });
+
+ await expect(
+ assertResumeRuntimeContentAllowed(createInput({}), dependencies),
+ ).rejects.toMatchObject({
+ name: 'AttachmentObjectNotFoundError',
+ fileId: 'deleted-file',
+ });
});
it('checks initialized agent content without loading checkpoint history', async () => {
@@ -146,6 +409,7 @@ describe('assertResumeRuntimeContentAllowed', () => {
await expect(assertResumeRuntimeContentAllowed(input, dependencies)).resolves.toEqual({
resolvedFiles: [],
+ checkpointFiles: [],
});
});
@@ -186,7 +450,64 @@ describe('assertResumeRuntimeContentAllowed', () => {
await expect(assertResumeRuntimeContentAllowed(input, dependencies)).resolves.toEqual({
resolvedFiles: [resolvedFile],
+ checkpointFiles: [],
+ });
+ });
+
+ it('reuses active-policy message and file hydration for checkpoint projection', async () => {
+ const dependencies = createDependencies();
+ dependencies.getAgentCheckpointer.mockResolvedValue({
+ getTuple: jest.fn().mockResolvedValue({
+ checkpoint: {
+ channel_values: {
+ messages: [
+ {
+ role: 'human',
+ additional_kwargs: { sourceMessageId: 'source-message' },
+ },
+ ],
+ },
+ },
+ }),
+ });
+ const resolvedFile = {
+ file_id: 'historical-file',
+ filename: 'history.txt',
+ type: 'text/plain',
+ text: 'Safe historical context',
+ };
+ dependencies.getMessages.mockResolvedValue([
+ {
+ messageId: 'source-message',
+ role: 'user',
+ isCreatedByUser: true,
+ text: 'Use the historical file',
+ files: [{ file_id: 'historical-file' }],
+ },
+ ]);
+ dependencies.getFiles.mockResolvedValue([resolvedFile]);
+ const input = {
+ ...createInput({
+ filters: {
+ files: {
+ pii: {
+ fields: ['extracted_text'],
+ starterPatterns: [],
+ uninspectable: 'block' as const,
+ },
+ },
+ },
+ }),
+ targetMessageId: 'source-message',
+ isTemporary: false,
+ };
+
+ await expect(assertResumeRuntimeContentAllowed(input, dependencies)).resolves.toEqual({
+ resolvedFiles: [resolvedFile],
+ checkpointFiles: [resolvedFile],
});
+ expect(dependencies.getMessages).toHaveBeenCalledTimes(1);
+ expect(dependencies.getFiles).toHaveBeenCalledTimes(1);
});
it('retains toolArguments coverage for checkpoint assistant tool calls', async () => {
@@ -242,7 +563,7 @@ describe('assertResumeRuntimeContentAllowed', () => {
await expect(
assertResumeRuntimeContentAllowed(contentPartInput, contentPartDependencies),
- ).resolves.toEqual({ resolvedFiles: [] });
+ ).resolves.toEqual({ resolvedFiles: [], checkpointFiles: [] });
const answerDependencies = createDependencies();
answerDependencies.getAgentCheckpointer.mockResolvedValue({
diff --git a/packages/api/src/agents/hitl/protection.ts b/packages/api/src/agents/hitl/protection.ts
index e0dfedaa6c..7008e67375 100644
--- a/packages/api/src/agents/hitl/protection.ts
+++ b/packages/api/src/agents/hitl/protection.ts
@@ -41,6 +41,7 @@ import type { TextContentFragment } from '~/protection/types';
import type { CheckAccessParams } from '~/middleware/access';
import {
assertModelBoundContent,
+ collectModelBoundHistoricalFileIdState,
hasModelBoundContentProtection,
type ModelBoundContentInput,
} from '~/middleware/modelBoundContent';
@@ -53,6 +54,7 @@ import { getResumeAgentSnapshot, getResumeContentInspection } from './inspection
import { extractStoredMessageContent } from '~/protection/adapters/submissions';
import { agentHasInlineMemoryTools, getMemoryAgentId } from '../memory';
import { LIBRECHAT_CHECKPOINT_NAMESPACE_KEY } from '../checkpointer';
+import { AttachmentObjectNotFoundError } from '~/files/encode/utils';
import { ASK_USER_QUESTION_TOOL_NAME } from './askUserQuestionTool';
import { ContentFilterError } from '~/middleware/contentFilter';
import { hasActiveFilePolicy } from '~/protection/files';
@@ -103,6 +105,14 @@ interface ResumeCheckpointMessage {
readonly metadata?: object;
readonly additional_kwargs?: {
readonly skillName?: string;
+ readonly sourceMessageId?: string;
+ readonly sourceMessageIds?: readonly string[];
+ readonly provenance?: {
+ readonly parts?: readonly {
+ readonly attribution?: string;
+ readonly sourceMessageId?: string;
+ }[];
+ };
readonly tool_calls?: readonly ResumeToolCall[];
};
readonly _getType?: () => string;
@@ -214,6 +224,7 @@ export type ResumeRuntimeContentProtectionDependencies = Pick<
export interface ResumeRuntimeContentProjection {
readonly resolvedFiles: ResumeContentInspection['hydratedFiles'];
+ readonly checkpointFiles: ResumeContentInspection['hydratedFiles'];
}
function hasResumeHistoryProtection(appConfig: ResumeProtectionConfig | undefined): boolean {
@@ -811,10 +822,18 @@ type AssertResumeModelBoundContentAllowedInput = Pick<
| 'checkpointNamespace'
> & {
readonly trustLiveFileContent?: boolean;
+ readonly checkpointMessages?: readonly ResumeCheckpointMessage[];
readonly agents?: ModelBoundContentInput['agents'];
readonly files?: ModelBoundContentInput['files'];
};
+interface ResumeModelBoundContentProjection {
+ readonly resolvedFiles: ResumeContentInspection['hydratedFiles'];
+ readonly sourceMessages: ResumeContentInspection['originalStoredMessages'];
+ readonly checkpointMessages: readonly ResumeCheckpointMessage[];
+ readonly historyLoaded: boolean;
+}
+
async function assertResumeModelBoundContentAllowed(
{
appConfig,
@@ -828,11 +847,12 @@ async function assertResumeModelBoundContentAllowed(
isTemporary,
checkpointNamespace = '',
trustLiveFileContent,
+ checkpointMessages: providedCheckpointMessages,
agents,
files,
}: AssertResumeModelBoundContentAllowedInput,
dependencies: ResumeRuntimeContentProtectionDependencies,
-): Promise<ResumeContentInspection['hydratedFiles']> {
+): Promise<ResumeModelBoundContentProjection> {
if (!hasResumeHistoryProtection(appConfig)) {
assertModelBoundContent({
filters: appConfig?.filters,
@@ -840,17 +860,24 @@ async function assertResumeModelBoundContentAllowed(
agents,
files,
});
- return [];
+ return {
+ resolvedFiles: [],
+ sourceMessages: storedMessages,
+ checkpointMessages: providedCheckpointMessages ?? [],
+ historyLoaded: false,
+ };
}
let checkpointMessages: readonly ResumeCheckpointMessage[];
try {
- checkpointMessages = await getResumeCheckpointMessages(
- appConfig,
- conversationId,
- checkpointNamespace,
- dependencies,
- );
+ checkpointMessages =
+ providedCheckpointMessages ??
+ (await getResumeCheckpointMessages(
+ appConfig,
+ conversationId,
+ checkpointNamespace,
+ dependencies,
+ ));
} catch {
throw new ContentTraversalLimitError();
}
@@ -880,7 +907,12 @@ async function assertResumeModelBoundContentAllowed(
resolvedFiles: contentInspection.hydratedFiles,
});
assertResumeToolContentAllowed(appConfig?.filters, checkpointMessages, seedContent, resumeValue);
- return contentInspection.hydratedFiles;
+ return {
+ resolvedFiles: contentInspection.hydratedFiles,
+ sourceMessages: contentInspection.originalStoredMessages,
+ checkpointMessages,
+ historyLoaded: true,
+ };
}
export async function assertResumeContentAllowed(
@@ -936,17 +968,170 @@ export async function assertResumeRuntimeContentAllowed(
input: AssertResumeRuntimeContentAllowedInput,
dependencies: ResumeRuntimeContentProtectionDependencies,
): Promise<ResumeRuntimeContentProjection> {
- if (!hasResumeContentProtection(input.appConfig)) {
- return { resolvedFiles: [] };
+ let checkpointMessages = hasResumeHistoryProtection(input.appConfig)
+ ? await getResumeCheckpointMessages(
+ input.appConfig,
+ input.conversationId,
+ input.checkpointNamespace ?? '',
+ dependencies,
+ )
+ : undefined;
+ const modelBoundProjection = hasResumeContentProtection(input.appConfig)
+ ? await assertResumeModelBoundContentAllowed(
+ {
+ ...input,
+ trustLiveFileContent: true,
+ checkpointMessages,
+ },
+ dependencies,
+ )
+ : undefined;
+ const resolvedFiles = modelBoundProjection?.resolvedFiles ?? [];
+ if (modelBoundProjection?.historyLoaded === true) {
+ checkpointMessages = modelBoundProjection.checkpointMessages;
}
- const resolvedFiles = await assertResumeModelBoundContentAllowed(
- {
- ...input,
- trustLiveFileContent: true,
- },
+ checkpointMessages ??= await getResumeCheckpointMessages(
+ input.appConfig,
+ input.conversationId,
+ input.checkpointNamespace ?? '',
dependencies,
);
- return { resolvedFiles };
+ const checkpointSourceMessageIds = new Set(
+ checkpointMessages
+ .flatMap((message) => {
+ const additionalKwargs = message.additional_kwargs;
+ return [
+ additionalKwargs?.sourceMessageId,
+ ...(Array.isArray(additionalKwargs?.sourceMessageIds)
+ ? additionalKwargs.sourceMessageIds
+ : []),
+ ...(Array.isArray(additionalKwargs?.provenance?.parts)
+ ? additionalKwargs.provenance.parts
+ .filter((part) => part?.attribution === 'user' || part?.attribution === 'tool')
+ .map((part) => part.sourceMessageId)
+ : []),
+ ];
+ })
+ .filter(
+ (messageId): messageId is string => typeof messageId === 'string' && messageId.length > 0,
+ ),
+ );
+ let sourceMessages = (modelBoundProjection?.sourceMessages ?? input.storedMessages).filter(
+ (message) => {
+ const messageId = message.messageId ?? message.id;
+ return messageId != null && checkpointSourceMessageIds.has(messageId);
+ },
+ );
+ const resolvedSourceMessageIds = new Set(
+ sourceMessages
+ .map((message) => message.messageId ?? message.id)
+ .filter((messageId): messageId is string => messageId != null),
+ );
+ const missingSourceMessageIds = [...checkpointSourceMessageIds].filter(
+ (messageId) => !resolvedSourceMessageIds.has(messageId),
+ );
+ if (
+ modelBoundProjection?.historyLoaded !== true &&
+ !input.isTemporary &&
+ missingSourceMessageIds.length > 0 &&
+ input.user?.id
+ ) {
+ const persistedMessages =
+ (await dependencies.getMessages({
+ conversationId: input.conversationId,
+ user: input.user.id,
+ })) ?? [];
+ const sourceMessagesById = new Map(
+ sourceMessages.map((message) => [message.messageId ?? message.id, message]),
+ );
+ for (const message of persistedMessages) {
+ const messageId = message.messageId ?? message.id;
+ if (messageId != null && checkpointSourceMessageIds.has(messageId)) {
+ sourceMessagesById.set(messageId, message);
+ }
+ }
+ sourceMessages = [...sourceMessagesById.values()];
+ }
+ const availableSourceMessageIds = new Set(
+ sourceMessages
+ .map((message) => message.messageId ?? message.id)
+ .filter((messageId): messageId is string => messageId != null),
+ );
+ const unresolvedSourceMessageId = [...checkpointSourceMessageIds].find(
+ (messageId) => !availableSourceMessageIds.has(messageId),
+ );
+ if (unresolvedSourceMessageId != null) {
+ throw new Error('A checkpoint source message is no longer available');
+ }
+ const checkpointFileInputs = [
+ ...checkpointMessages.map((message) => ({
+ files: message.files,
+ content: message.content,
+ })),
+ ...sourceMessages.map((message) => ({ files: message.files, content: message.content })),
+ ] as ResumeContentInspectionInput['supplementalMessages'];
+ const nonSteerCheckpointFileIds = collectModelBoundHistoricalFileIdState(
+ checkpointFileInputs.map((message) => ({
+ files: message?.files,
+ content: Array.isArray(message?.content)
+ ? message.content.filter((part) => part?.type !== 'steer')
+ : message?.content,
+ })),
+ ).fileIds;
+ const checkpointSteerFileIds: string[] = [];
+ for (const message of checkpointFileInputs) {
+ if (!Array.isArray(message?.content)) {
+ continue;
+ }
+ for (const part of message.content) {
+ if (part?.type !== 'steer' || !Array.isArray(part.files)) {
+ continue;
+ }
+ for (const file of part.files) {
+ if (typeof file?.file_id === 'string' && file.file_id.length > 0) {
+ checkpointSteerFileIds.push(file.file_id);
+ }
+ }
+ }
+ }
+ const checkpointFileIdOccurrences = [...nonSteerCheckpointFileIds, ...checkpointSteerFileIds];
+ const checkpointFileIds = new Set(checkpointFileIdOccurrences);
+ const resolvedFilesById = new Map(
+ resolvedFiles
+ .filter((file) => checkpointFileIds.has(file.file_id ?? ''))
+ .map((file) => [file.file_id, file]),
+ );
+ const missingCheckpointFileIds = [...checkpointFileIds].filter(
+ (fileId) => !resolvedFilesById.has(fileId),
+ );
+ const missingCheckpointFileIdSet = new Set(missingCheckpointFileIds);
+ if (missingCheckpointFileIds.length > 0 && input.user?.id) {
+ const ownerFiles =
+ (await dependencies.getFiles(
+ {
+ file_id: { $in: missingCheckpointFileIds },
+ user: input.user.id,
+ ...(input.user.tenantId != null && { tenantId: input.user.tenantId }),
+ },
+ {},
+ {},
+ )) ?? [];
+ for (const file of ownerFiles) {
+ if (missingCheckpointFileIdSet.has(file.file_id ?? '')) {
+ resolvedFilesById.set(file.file_id, file);
+ }
+ }
+ }
+ const checkpointFiles = checkpointFileIdOccurrences
+ .map((fileId) => resolvedFilesById.get(fileId))
+ .filter((file): file is NonNullable<typeof file> => file != null);
+ if ([...checkpointFileIds].some((fileId) => !resolvedFilesById.has(fileId))) {
+ const unresolvedFileId = [...checkpointFileIds].find(
+ (fileId) => !resolvedFilesById.has(fileId),
+ );
+ throw new AttachmentObjectNotFoundError(unresolvedFileId ?? 'unknown');
+ }
+ return { resolvedFiles, checkpointFiles };
}
export function getUserFacingResumeError(
diff --git a/packages/api/src/agents/initialize.ts b/packages/api/src/agents/initialize.ts
index 4fc3a0a5a6..863179d7f8 100644
--- a/packages/api/src/agents/initialize.ts
+++ b/packages/api/src/agents/initialize.ts
@@ -92,6 +92,7 @@ import {
} from './errors';
import { extractAgentContent, extractSkillContent } from '../protection/adapters/submissions';
import { createConfiguredContentInspector, inspectContent } from '../protection/runtime';
+import { assertAgentAttachmentLimits, isModelBoundAttachmentFile } from './attachments';
import { assertModelBoundContent } from '../middleware/modelBoundContent';
import { registerMemoryTools, memoryToolUsageGuard } from './memory';
import { applyIntentLabels, sanitizeIntentLabels } from './intent';
@@ -1204,6 +1205,17 @@ export async function initializeAgent(
files: currentFiles,
endpoint: agent.endpoint ?? '',
endpointType,
+ skipTotalSizeLimit: true,
+ preserveTextSources: true,
+ });
+ const requestUsageFileIds = new Set(requestUsageFiles.map((file) => file.file_id));
+ assertAgentAttachmentLimits({
+ attachments: currentFiles.filter(
+ (file) => requestUsageFileIds.has(file.file_id) && isModelBoundAttachmentFile(file),
+ ),
+ fileConfig: appConfig?.fileConfig,
+ endpoint: agent.endpoint ?? '',
+ endpointType,
});
}
diff --git a/packages/api/src/agents/steering/__tests__/media.spec.ts b/packages/api/src/agents/steering/__tests__/media.spec.ts
index 0951518156..acc1ff7e57 100644
--- a/packages/api/src/agents/steering/__tests__/media.spec.ts
+++ b/packages/api/src/agents/steering/__tests__/media.spec.ts
@@ -2,6 +2,7 @@ import type { IMongoFile } from '@librechat/data-schemas';
import type { SteerFileFetcher } from '../request';
import type { SteerMediaClient } from '../media';
import { buildSteerMedia, collectSteerStampTargets, stampSteerPartMedia } from '../media';
+import { AttachmentObjectNotFoundError } from '~/files/encode/utils';
jest.spyOn(console, 'log').mockImplementation();
@@ -286,6 +287,35 @@ describe('stampSteerPartMedia', () => {
expect(steerPart).not.toHaveProperty('media');
});
+ it('propagates a missing attachment object instead of replaying text only', async () => {
+ const getFiles: SteerFileFetcher = jest.fn(async () => []);
+ const client = createClient();
+ client.processAttachments = jest
+ .fn()
+ .mockRejectedValue(new AttachmentObjectNotFoundError('missing-object'));
+ const steerPart = {
+ type: 'steer',
+ steer: 'read the missing file',
+ steerId: 'missing-steer',
+ files: [{ file_id: 'missing-object' }],
+ };
+ const message = { role: 'assistant', content: [steerPart] };
+
+ await expect(
+ stampSteerPartMedia({
+ client,
+ user,
+ payload: [message],
+ docsById: new Map([['missing-object', imageDoc]]),
+ getFiles,
+ }),
+ ).rejects.toMatchObject({
+ code: 'ATTACHMENT_OBJECT_NOT_FOUND',
+ fileId: 'missing-object',
+ });
+ expect(steerPart).not.toHaveProperty('media');
+ });
+
it('stamps merged text media for a quote-bearing part without files', async () => {
const getFiles: SteerFileFetcher = jest.fn(async () => []);
const client = createClient();
diff --git a/packages/api/src/agents/steering/__tests__/runtime.spec.ts b/packages/api/src/agents/steering/__tests__/runtime.spec.ts
index ddc4d04355..a922838ce9 100644
--- a/packages/api/src/agents/steering/__tests__/runtime.spec.ts
+++ b/packages/api/src/agents/steering/__tests__/runtime.spec.ts
@@ -457,10 +457,12 @@ describe('createSteerDrainHook', () => {
files: [{ file_id: 'f-gone' }],
});
+ const onMediaError = jest.fn();
const hook = createSteerDrainHook({
streamId,
jobCreatedAt: job.createdAt,
applySteer: jest.fn(),
+ onMediaError,
buildMedia: async () => {
throw new Error('encode failed');
},
@@ -470,6 +472,10 @@ describe('createSteerDrainHook', () => {
expect(output.injectedMessages).toEqual([
{ role: 'user', content: 'words survive', source: 'steer' },
]);
+ expect(onMediaError).toHaveBeenCalledWith(
+ expect.objectContaining({ steerId: 's1' }),
+ expect.objectContaining({ message: 'encode failed' }),
+ );
});
});
diff --git a/packages/api/src/agents/steering/media.ts b/packages/api/src/agents/steering/media.ts
index 879a7ad2d1..4536f5678f 100644
--- a/packages/api/src/agents/steering/media.ts
+++ b/packages/api/src/agents/steering/media.ts
@@ -8,6 +8,7 @@ import type { SteerFileFetcher } from './request';
import type { SteerMediaResult } from './runtime';
import type { SteerRequestUser } from './refs';
import { toSteerFileRef, collectFileIds, buildOwnerFilter } from './refs';
+import { isAttachmentObjectNotFoundError } from '~/files/encode/utils';
import { getReferencedQuotes, mergeQuotedText } from '~/utils';
import { prependFileContext } from '../client';
@@ -305,6 +306,9 @@ export async function stampSteerPartMedia({
),
);
} catch (error) {
+ if (isAttachmentObjectNotFoundError(error)) {
+ throw error;
+ }
logger.warn(
`[stampSteerPartMedia] Failed to re-encode steer media (steer=${part.steerId}); replaying text only`,
error,
diff --git a/packages/api/src/agents/steering/runtime.ts b/packages/api/src/agents/steering/runtime.ts
index aea73d4a57..264b2564da 100644
--- a/packages/api/src/agents/steering/runtime.ts
+++ b/packages/api/src/agents/steering/runtime.ts
@@ -80,6 +80,8 @@ export interface SteerDrainHookOptions {
* never dropped because an attachment could not be encoded.
*/
buildMedia?: (item: SteerQueueItem) => Promise<SteerMediaResult | undefined>;
+ /** Repairs the durable steer part when media degrades to text-only. */
+ onMediaError?: (item: SteerQueueItem, error: unknown) => void | Promise<void>;
}
/**
@@ -102,7 +104,7 @@ async function drainAndBuildInjections(
claim: () => Promise<SteerQueueItem[]> = () =>
GenerationJobManager.steering.drain(opts.streamId, opts.jobCreatedAt),
): Promise<InjectedMessage[]> {
- const { streamId, jobCreatedAt, applySteer, buildMedia } = opts;
+ const { streamId, jobCreatedAt, applySteer, buildMedia, onMediaError } = opts;
// The replacement guard lives INSIDE the store's atomic drain: a separate
// check-then-drain could still consume a replacement job's queue if
// createJob landed between the two steps.
@@ -181,6 +183,14 @@ async function drainAndBuildInjections(
`[steering] Failed to encode steer media for ${streamId} steer=${item.steerId}; injecting text only:`,
error,
);
+ try {
+ await onMediaError?.(item, error);
+ } catch (repairError) {
+ logger.error(
+ `[steering] Failed to repair text-only steer persistence for ${streamId} steer=${item.steerId}:`,
+ repairError,
+ );
+ }
}
}
/** The media path already merged quotes into its text part; the plain
diff --git a/packages/api/src/files/encode/audio.ts b/packages/api/src/files/encode/audio.ts
index 89f4f31df8..fa155cd3b3 100644
--- a/packages/api/src/files/encode/audio.ts
+++ b/packages/api/src/files/encode/audio.ts
@@ -2,7 +2,11 @@ import { Providers } from '@librechat/agents';
import { isDocumentSupportedProvider } from 'librechat-data-provider';
import type { IMongoFile } from '@librechat/data-schemas';
import type { ServerRequest, StrategyFunctions, AudioResult } from '~/types';
-import { getFileStream, getConfiguredFileSizeLimit } from './utils';
+import {
+ getFileStream,
+ getConfiguredFileSizeLimit,
+ isAttachmentObjectNotFoundError,
+} from './utils';
import { validateAudio } from '~/files/validation';
import { runGuardedEncode } from './memoryGuard';
@@ -40,6 +44,9 @@ export async function encodeAndFormatAudios(
for (const settledResult of results) {
if (settledResult.status === 'rejected') {
+ if (isAttachmentObjectNotFoundError(settledResult.reason)) {
+ throw settledResult.reason;
+ }
console.error('Audio processing failed:', settledResult.reason);
continue;
}
diff --git a/packages/api/src/files/encode/document.spec.ts b/packages/api/src/files/encode/document.spec.ts
index 62bd974075..295bafe769 100644
--- a/packages/api/src/files/encode/document.spec.ts
+++ b/packages/api/src/files/encode/document.spec.ts
@@ -14,6 +14,7 @@ jest.mock('~/files/validation', () => ({
jest.mock('./utils', () => ({
getFileStream: jest.fn(),
getConfiguredFileSizeLimit: jest.fn(),
+ isAttachmentObjectNotFoundError: jest.fn(() => false),
}));
import { validatePdf, validateBedrockDocument } from '~/files/validation';
diff --git a/packages/api/src/files/encode/document.ts b/packages/api/src/files/encode/document.ts
index b225841258..4ad0780ca6 100644
--- a/packages/api/src/files/encode/document.ts
+++ b/packages/api/src/files/encode/document.ts
@@ -15,8 +15,12 @@ import type {
DocumentResult,
ServerRequest,
} from '~/types';
+import {
+ getFileStream,
+ getConfiguredFileSizeLimit,
+ isAttachmentObjectNotFoundError,
+} from './utils';
import { validatePdf, validateBedrockDocument } from '~/files/validation';
-import { getFileStream, getConfiguredFileSizeLimit } from './utils';
import { runGuardedEncode } from './memoryGuard';
/** Anthropic only accepts PDFs as base64 documents; textual types must use a text source */
@@ -209,6 +213,9 @@ export async function encodeAndFormatDocuments(
for (const settledResult of results) {
if (settledResult.status === 'rejected') {
+ if (isAttachmentObjectNotFoundError(settledResult.reason)) {
+ throw settledResult.reason;
+ }
console.error('Document processing failed:', settledResult.reason);
continue;
}
diff --git a/packages/api/src/files/encode/index.ts b/packages/api/src/files/encode/index.ts
index ca4949cbf0..447ad527c8 100644
--- a/packages/api/src/files/encode/index.ts
+++ b/packages/api/src/files/encode/index.ts
@@ -2,3 +2,4 @@ export * from './audio';
export * from './document';
export * from './video';
export * from './memoryGuard';
+export * from './utils';
diff --git a/packages/api/src/files/encode/utils.spec.ts b/packages/api/src/files/encode/utils.spec.ts
new file mode 100644
index 0000000000..c2090055ed
--- /dev/null
+++ b/packages/api/src/files/encode/utils.spec.ts
@@ -0,0 +1,79 @@
+import { Readable } from 'node:stream';
+import type { IMongoFile } from '@librechat/data-schemas';
+import type { ServerRequest, StrategyFunctions } from '~/types';
+import { AttachmentObjectNotFoundError, getFileStream } from './utils';
+
+const file = {
+ file_id: 'file-1',
+ filepath: 's3://bucket/file-1',
+ filename: 'document.pdf',
+ type: 'application/pdf',
+ bytes: 4,
+ source: 's3',
+} as IMongoFile;
+
+describe('getFileStream', () => {
+ it('maps a missing storage object to a user-actionable attachment error', async () => {
+ const getDownloadStream = jest.fn().mockRejectedValue({
+ name: 'NoSuchKey',
+ $metadata: { httpStatusCode: 404 },
+ });
+
+ await expect(
+ getFileStream(
+ {} as ServerRequest,
+ file,
+ {},
+ () => ({ getDownloadStream }) as StrategyFunctions,
+ ),
+ ).rejects.toEqual(
+ expect.objectContaining<Partial<AttachmentObjectNotFoundError>>({
+ code: 'ATTACHMENT_OBJECT_NOT_FOUND',
+ fileId: 'file-1',
+ }),
+ );
+ });
+
+ it.each([{ response: { status: 404 } }, { status: 404 }, { statusCode: 404 }])(
+ 'maps HTTP-style missing storage errors to the attachment error',
+ async (storageError) => {
+ const getDownloadStream = jest.fn().mockRejectedValue(storageError);
+
+ await expect(
+ getFileStream(
+ {} as ServerRequest,
+ file,
+ {},
+ () => ({ getDownloadStream }) as StrategyFunctions,
+ ),
+ ).rejects.toMatchObject({ code: 'ATTACHMENT_OBJECT_NOT_FOUND', fileId: 'file-1' });
+ },
+ );
+
+ it('preserves non-missing storage failures', async () => {
+ const failure = new Error('storage unavailable');
+ const getDownloadStream = jest.fn().mockRejectedValue(failure);
+
+ await expect(
+ getFileStream(
+ {} as ServerRequest,
+ file,
+ {},
+ () => ({ getDownloadStream }) as StrategyFunctions,
+ ),
+ ).rejects.toBe(failure);
+ });
+
+ it('encodes available storage content', async () => {
+ const getDownloadStream = jest.fn().mockResolvedValue(Readable.from(Buffer.from('data')));
+
+ await expect(
+ getFileStream(
+ {} as ServerRequest,
+ file,
+ {},
+ () => ({ getDownloadStream }) as StrategyFunctions,
+ ),
+ ).resolves.toMatchObject({ content: Buffer.from('data').toString('base64') });
+ });
+});
diff --git a/packages/api/src/files/encode/utils.ts b/packages/api/src/files/encode/utils.ts
index be1116519b..f0e63cbad0 100644
--- a/packages/api/src/files/encode/utils.ts
+++ b/packages/api/src/files/encode/utils.ts
@@ -5,6 +5,44 @@ import type { IMongoFile } from '@librechat/data-schemas';
import type { ServerRequest, StrategyFunctions, ProcessedFile } from '~/types';
import { resolveDownloadPath } from '~/storage/path';
+export class AttachmentObjectNotFoundError extends Error {
+ readonly code = 'ATTACHMENT_OBJECT_NOT_FOUND';
+
+ constructor(readonly fileId: string | undefined) {
+ super('An attached file is no longer available. Remove it, upload it again, and retry.');
+ this.name = 'AttachmentObjectNotFoundError';
+ }
+}
+
+export function isAttachmentObjectNotFoundError(
+ error: unknown,
+): error is AttachmentObjectNotFoundError {
+ return error instanceof AttachmentObjectNotFoundError;
+}
+
+function isStorageNotFoundError(error: unknown): boolean {
+ if (typeof error !== 'object' || error == null) {
+ return false;
+ }
+ const storageError = error as {
+ name?: string;
+ code?: string;
+ status?: number;
+ statusCode?: number;
+ response?: { status?: number };
+ $metadata?: { httpStatusCode?: number };
+ };
+ return (
+ storageError.name === 'NoSuchKey' ||
+ storageError.code === 'NoSuchKey' ||
+ storageError.code === 'ENOENT' ||
+ storageError.status === 404 ||
+ storageError.statusCode === 404 ||
+ storageError.response?.status === 404 ||
+ storageError.$metadata?.httpStatusCode === 404
+ );
+}
+
/**
* Extracts the configured file size limit for a specific provider from fileConfig
* @param req - The server request object containing config
@@ -56,21 +94,28 @@ export async function getFileStream(
}
const { getDownloadStream } = encodingMethods[source];
- const stream = await getDownloadStream(req, resolveDownloadPath(file));
- let buffer: Buffer | null = await getStream.buffer(stream);
- const content = buffer.toString('base64');
- buffer = null;
+ try {
+ const stream = await getDownloadStream(req, resolveDownloadPath(file));
+ let buffer: Buffer | null = await getStream.buffer(stream);
+ const content = buffer.toString('base64');
+ buffer = null;
- return {
- file,
- content,
- metadata: {
- file_id: file.file_id,
- temp_file_id: file.temp_file_id,
- filepath: file.filepath,
- source: file.source,
- filename: file.filename,
- type: file.type,
- },
- };
+ return {
+ file,
+ content,
+ metadata: {
+ file_id: file.file_id,
+ temp_file_id: file.temp_file_id,
+ filepath: file.filepath,
+ source: file.source,
+ filename: file.filename,
+ type: file.type,
+ },
+ };
+ } catch (error) {
+ if (isStorageNotFoundError(error)) {
+ throw new AttachmentObjectNotFoundError(file.file_id);
+ }
+ throw error;
+ }
}
diff --git a/packages/api/src/files/encode/video.ts b/packages/api/src/files/encode/video.ts
index 26c8d007d5..52a9331c8d 100644
--- a/packages/api/src/files/encode/video.ts
+++ b/packages/api/src/files/encode/video.ts
@@ -2,7 +2,11 @@ import { Providers } from '@librechat/agents';
import { isDocumentSupportedProvider } from 'librechat-data-provider';
import type { IMongoFile } from '@librechat/data-schemas';
import type { ServerRequest, StrategyFunctions, VideoResult } from '~/types';
-import { getFileStream, getConfiguredFileSizeLimit } from './utils';
+import {
+ getFileStream,
+ getConfiguredFileSizeLimit,
+ isAttachmentObjectNotFoundError,
+} from './utils';
import { validateVideo } from '~/files/validation';
import { runGuardedEncode } from './memoryGuard';
@@ -40,6 +44,9 @@ export async function encodeAndFormatVideos(
for (const settledResult of results) {
if (settledResult.status === 'rejected') {
+ if (isAttachmentObjectNotFoundError(settledResult.reason)) {
+ throw settledResult.reason;
+ }
console.error('Video processing failed:', settledResult.reason);
continue;
}
diff --git a/packages/api/src/files/filter.spec.ts b/packages/api/src/files/filter.spec.ts
index e7858f486f..e74933de24 100644
--- a/packages/api/src/files/filter.spec.ts
+++ b/packages/api/src/files/filter.spec.ts
@@ -1,6 +1,6 @@
import { Types } from 'mongoose';
import { Providers } from '@librechat/agents';
-import { EModelEndpoint } from 'librechat-data-provider';
+import { EModelEndpoint, FileSources } from 'librechat-data-provider';
import type { IMongoFile } from '@librechat/data-schemas';
import type { ServerRequest } from '~/types';
import { filterFilesByEndpointConfig } from './filter';
@@ -847,6 +847,31 @@ describe('filterFilesByEndpointConfig', () => {
expect(result).toEqual([pdfFile, pngFile]);
});
+ it('can preserve extracted-text sources that bypass provider MIME encoding', () => {
+ const req = {
+ config: {
+ fileConfig: {
+ endpoints: {
+ [Providers.OPENAI]: { supportedMimeTypes: ['^application/pdf$'] },
+ },
+ },
+ },
+ } as unknown as ServerRequest;
+ const extractedText = {
+ ...createMockFile('notes.txt'),
+ source: FileSources.text,
+ type: 'text/plain',
+ } as IMongoFile;
+
+ expect(
+ filterFilesByEndpointConfig(req, {
+ files: [extractedText],
+ endpoint: Providers.OPENAI,
+ preserveTextSources: true,
+ }),
+ ).toEqual([extractedText]);
+ });
+
it('should keep all files when supportedMimeTypes is not set', () => {
const req = {
config: {
@@ -973,6 +998,30 @@ describe('filterFilesByEndpointConfig', () => {
});
describe('total size limit filtering', () => {
+ it('can preserve aggregate survivors for explicit admission checks', () => {
+ const req = {
+ config: {
+ fileConfig: {
+ endpoints: {
+ [Providers.OPENAI]: { totalSizeLimit: 1 },
+ },
+ },
+ },
+ } as unknown as ServerRequest;
+ const files = [
+ { ...createMockFile('first.pdf'), bytes: 600_000 } as IMongoFile,
+ { ...createMockFile('second.pdf'), bytes: 600_000 } as IMongoFile,
+ ];
+
+ expect(
+ filterFilesByEndpointConfig(req, {
+ files,
+ endpoint: Providers.OPENAI,
+ skipTotalSizeLimit: true,
+ }),
+ ).toEqual(files);
+ });
+
it('should filter files when total size exceeds totalSizeLimit', () => {
const req = {
config: {
diff --git a/packages/api/src/files/filter.ts b/packages/api/src/files/filter.ts
index 0e02315955..1d2e58cd53 100644
--- a/packages/api/src/files/filter.ts
+++ b/packages/api/src/files/filter.ts
@@ -1,4 +1,9 @@
-import { getEndpointFileConfig, mergeFileConfig, fileConfig } from 'librechat-data-provider';
+import {
+ FileSources,
+ getEndpointFileConfig,
+ mergeFileConfig,
+ fileConfig,
+} from 'librechat-data-provider';
import type { AppConfig, IMongoFile } from '@librechat/data-schemas';
import type { RegexLike } from 'librechat-data-provider';
import type { ServerRequest } from '~/types';
@@ -35,6 +40,8 @@ export function filterFilesByEndpointConfig(
files: IMongoFile[] | undefined;
endpoint?: string | null;
endpointType?: string | null;
+ skipTotalSizeLimit?: boolean;
+ preserveTextSources?: boolean;
},
): IMongoFile[] {
return filterFilesByEndpointRuntimeConfig(req.config, params);
@@ -47,9 +54,17 @@ export function filterFilesByEndpointRuntimeConfig(
files: IMongoFile[] | undefined;
endpoint?: string | null;
endpointType?: string | null;
+ skipTotalSizeLimit?: boolean;
+ preserveTextSources?: boolean;
},
): IMongoFile[] {
- const { files, endpoint, endpointType } = params;
+ const {
+ files,
+ endpoint,
+ endpointType,
+ skipTotalSizeLimit = false,
+ preserveTextSources = false,
+ } = params;
if (!files || files.length === 0) {
return [];
@@ -85,12 +100,15 @@ export function filterFilesByEndpointRuntimeConfig(
/** Filter by MIME type */
if (supportedMimeTypes && supportedMimeTypes.length > 0) {
filteredFiles = filteredFiles.filter((file) => {
- return isMimeTypeSupported(file.type, supportedMimeTypes);
+ return (
+ (preserveTextSources && (file.source ?? FileSources.local) === FileSources.text) ||
+ isMimeTypeSupported(file.type, supportedMimeTypes)
+ );
});
}
/** Filter by total size limit - keep files until total exceeds limit */
- if (totalSizeLimit !== undefined && totalSizeLimit > 0) {
+ if (!skipTotalSizeLimit && totalSizeLimit !== undefined && totalSizeLimit > 0) {
let totalSize = 0;
const withinTotalLimit: IMongoFile[] = [];
diff --git a/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.ts b/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.ts
index b7bb784812..4b5889fe97 100644
--- a/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.ts
+++ b/packages/api/src/stream/__tests__/RedisJobStore.stream_integration.spec.ts
@@ -4066,6 +4066,19 @@ describe('RedisJobStore Integration Tests', () => {
event: 'on_message_delta',
data: { id: 'step-1', delta: { content: { type: 'text', text: 'Before steer.' } } },
},
+ {
+ event: 'on_steer_applied',
+ data: {
+ steerId: 'steer-1',
+ index: 1,
+ part: {
+ type: 'steer',
+ steer: 'change course',
+ steerId: 'steer-1',
+ files: [{ file_id: 'rejected-file' }],
+ },
+ },
+ },
{
event: 'on_steer_applied',
data: {
@@ -4097,6 +4110,7 @@ describe('RedisJobStore Integration Tests', () => {
const parts = result!.content as Array<{ type?: string; steer?: string; text?: unknown }>;
expect(parts).toHaveLength(3);
expect(parts[1]).toMatchObject({ type: 'steer', steer: 'change course' });
+ expect(parts[1]).not.toHaveProperty('files');
expect(parts[0]?.type).toBe('text');
expect(parts[2]?.type).toBe('text');
diff --git a/packages/api/src/stream/implementations/RedisJobStore.ts b/packages/api/src/stream/implementations/RedisJobStore.ts
index b34f180055..86f5502a0b 100644
--- a/packages/api/src/stream/implementations/RedisJobStore.ts
+++ b/packages/api/src/stream/implementations/RedisJobStore.ts
@@ -3686,7 +3686,7 @@ export class RedisJobStore implements IJobStoreV2 {
if (chunks.length === 0) {
return parts;
}
- const steers: Array<{ index: number; part: Agents.MessageContentComplex }> = [];
+ const steersByIndex = new Map<number, Agents.MessageContentComplex>();
const labelsByIndex = new Map<number, Agents.MessageContentComplex>();
const reasoningStepsByIndex = new Map<number, string>();
const reasoningAttemptsByIndex = new Map<number, ReasoningAttemptOverlay>();
@@ -3715,7 +3715,7 @@ export class RedisJobStore implements IJobStoreV2 {
part?: Agents.MessageContentComplex;
};
if (typeof steerData.index === 'number' && steerData.part != null) {
- steers.push({ index: steerData.index, part: steerData.part });
+ steersByIndex.set(steerData.index, steerData.part);
}
continue;
}
@@ -3777,7 +3777,7 @@ export class RedisJobStore implements IJobStoreV2 {
}
}
if (
- steers.length === 0 &&
+ steersByIndex.size === 0 &&
labelsByIndex.size === 0 &&
reasoningStepsByIndex.size === 0 &&
reasoningAttemptHighWater === 0 &&
@@ -3786,7 +3786,7 @@ export class RedisJobStore implements IJobStoreV2 {
return parts;
}
const inserts = [
- ...steers,
+ ...[...steersByIndex.entries()].map(([index, part]) => ({ index, part })),
...[...labelsByIndex.entries()].map(([index, part]) => ({ index, part })),
];
inserts.sort((a, b) => a.index - b.index);
diff --git a/packages/data-provider/src/file-config.spec.ts b/packages/data-provider/src/file-config.spec.ts
index 3bd44a6a1a..414e3f1d4d 100644
--- a/packages/data-provider/src/file-config.spec.ts
+++ b/packages/data-provider/src/file-config.spec.ts
@@ -1736,3 +1736,22 @@ describe('fileConfigSchema clientImageResize', () => {
expect(result.success).toBe(false);
});
});
+
+describe('agent attachment context limits', () => {
+ it('keeps the turn-memory ceiling separate from agent upload storage', () => {
+ expect(baseFileConfig.fileContextSizeLimit).toBe(128 * 1024 * 1024);
+ expect(baseFileConfig.endpoints[EModelEndpoint.agents].totalSizeLimit).toBe(512 * 1024 * 1024);
+ });
+
+ it('validates and merges an aggregate model-context size limit in MB', () => {
+ expect(fileConfigSchema.safeParse({ fileContextSizeLimit: 64 }).success).toBe(true);
+ expect(mergeFileConfig({ fileContextSizeLimit: 64 }).fileContextSizeLimit).toBe(
+ 64 * 1024 * 1024,
+ );
+ });
+
+ it('validates and merges an aggregate extracted-text character limit', () => {
+ expect(fileConfigSchema.safeParse({ fileContextCharLimit: 250_000 }).success).toBe(true);
+ expect(mergeFileConfig({ fileContextCharLimit: 250_000 }).fileContextCharLimit).toBe(250_000);
+ });
+});
diff --git a/packages/data-provider/src/file-config.ts b/packages/data-provider/src/file-config.ts
index 133174dbe7..2084f66ba0 100644
--- a/packages/data-provider/src/file-config.ts
+++ b/packages/data-provider/src/file-config.ts
@@ -450,6 +450,8 @@ export const mbToBytes = (mb: number): number => mb * megabyte;
const defaultSizeLimit = mbToBytes(512);
const defaultSkillImportSizeLimit = mbToBytes(50);
const defaultTokenLimit = 100000;
+const defaultContextSizeLimit = mbToBytes(128);
+const defaultContextCharLimit = 1_000_000;
const assistantsFileConfig = {
fileLimit: 10,
fileSizeLimit: defaultSizeLimit,
@@ -484,6 +486,8 @@ export const fileConfig = {
serverFileSizeLimit: defaultSizeLimit,
avatarSizeLimit: mbToBytes(2),
fileTokenLimit: defaultTokenLimit,
+ fileContextSizeLimit: defaultContextSizeLimit,
+ fileContextCharLimit: defaultContextCharLimit,
clientImageResize: {
enabled: false,
maxWidth: 1900,
@@ -525,6 +529,8 @@ export const fileConfigSchema = z.object({
serverFileSizeLimit: z.number().min(0).optional(),
avatarSizeLimit: z.number().min(0).optional(),
fileTokenLimit: z.number().min(0).optional(),
+ fileContextSizeLimit: z.number().min(0).optional(),
+ fileContextCharLimit: z.number().min(0).optional(),
imageGeneration: z
.object({
percentage: z.number().min(0).max(100).optional(),
@@ -1014,6 +1020,14 @@ export function mergeFileConfig(dynamic: z.infer<typeof fileConfigSchema> | unde
mergedConfig.fileTokenLimit = dynamic.fileTokenLimit;
}
+ if (dynamic.fileContextSizeLimit !== undefined) {
+ mergedConfig.fileContextSizeLimit = mbToBytes(dynamic.fileContextSizeLimit);
+ }
+
+ if (dynamic.fileContextCharLimit !== undefined) {
+ mergedConfig.fileContextCharLimit = dynamic.fileContextCharLimit;
+ }
+
if (dynamic.skills?.fileSizeLimit !== undefined) {
mergedConfig.skills = {
...mergedConfig.skills,
diff --git a/packages/data-provider/src/types/files.ts b/packages/data-provider/src/types/files.ts
index 845a4964cf..1732e0458f 100644
--- a/packages/data-provider/src/types/files.ts
+++ b/packages/data-provider/src/types/files.ts
@@ -58,6 +58,10 @@ export type FileConfig = {
fileSizeLimit?: number;
};
fileTokenLimit?: number;
+ /** Maximum aggregate model-bound attachment bytes admitted into one agent turn. */
+ fileContextSizeLimit?: number;
+ /** Maximum aggregate extracted-text characters admitted into one agent turn. */
+ fileContextCharLimit?: number;
serverFileSizeLimit?: number;
avatarSizeLimit?: number;
clientImageResize?: {
@@ -89,6 +93,8 @@ export type FileConfigInput = {
};
serverFileSizeLimit?: number;
avatarSizeLimit?: number;
+ fileContextSizeLimit?: number;
+ fileContextCharLimit?: number;
clientImageResize?: {
enabled?: boolean;
maxWidth?: number;