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

🧷 feat: Carry Ask User Answers Past Compaction (#15944)

Danny Aviladea7346d721f
diff --git a/api/app/clients/BaseClient.js b/api/app/clients/BaseClient.js
index 4835f9ad80..a685ee3091 100644
--- a/api/app/clients/BaseClient.js
+++ b/api/app/clients/BaseClient.js
@@ -1239,6 +1239,9 @@ class BaseClient {
}
const messages = (await db.getMessages({ conversationId, user: this.user })) ?? [];
+ /** A client that reads beyond the walk below (which stops at a checkpoint
+ * summary) receives every row here; the rest keep nothing. */
+ this.onHistoryLoaded?.(messages);
if (messages.length === 0) {
return [];
diff --git a/api/server/controllers/agents/__tests__/client.retainedAnswers.spec.js b/api/server/controllers/agents/__tests__/client.retainedAnswers.spec.js
new file mode 100644
index 0000000000..aa0f035dbf
--- /dev/null
+++ b/api/server/controllers/agents/__tests__/client.retainedAnswers.spec.js
@@ -0,0 +1,436 @@
+const mockCreateRun = jest.fn();
+const mockRuntimeCounter = jest.fn((counter) => counter);
+const mockCountFormattedMessageTokens = jest.fn(
+ (message) => JSON.stringify(message?.content ?? '').length,
+);
+const mockFormatAgentMessages = jest.fn(() => ({
+ messages: [],
+ indexTokenCountMap: {},
+ summary: undefined,
+ boundaryTokenAdjustment: undefined,
+}));
+const mockFormatInstructions = jest.fn().mockResolvedValue('');
+
+jest.mock('@librechat/agents', () => ({
+ ...jest.requireActual('@librechat/agents'),
+ createMetadataAggregator: () => ({ handleLLMEnd: jest.fn(), collected: [] }),
+ formatAgentMessages: (...args) => mockFormatAgentMessages(...args),
+}));
+
+jest.mock('@librechat/api', () => ({
+ ...jest.requireActual('@librechat/api'),
+ checkAccess: jest.fn(),
+ withRetainedAnswerTokenCounter: (...args) => mockRuntimeCounter(...args),
+ prepareRetainedAnswers: (input) =>
+ jest.requireActual('@librechat/api').prepareRetainedAnswers({
+ ...input,
+ countTokens: (text) => mockCountFormattedMessageTokens({ role: 'user', content: text }),
+ }),
+ createRun: (...args) => mockCreateRun(...args),
+ countFormattedMessageTokens: (...args) => mockCountFormattedMessageTokens(...args),
+ countTokens: jest.fn((text) => Math.ceil(String(text ?? '').length / 4)),
+ createCachedTokenCounter: jest.fn(async () => mockCountFormattedMessageTokens),
+ getAgentCheckpointer: jest.fn(),
+ hasDurableAgentInterruptCheckpoint: jest.fn().mockResolvedValue(true),
+ initializeAgent: jest.fn(),
+ isHITLEnabled: jest.fn(() => false),
+ loadAgent: jest.fn(),
+ maybePrewarmCodeSandbox: jest.fn(),
+}));
+
+jest.mock('~/server/services/Config', () => ({ getMCPServerTools: jest.fn() }));
+jest.mock('~/server/services/MCP', () => ({
+ resolveConfigServers: jest.fn().mockResolvedValue({}),
+}));
+jest.mock('~/models', () => ({
+ bulkInsertTransactions: jest.fn(),
+ getCacheMultiplier: jest.fn(),
+ getAgent: jest.fn(),
+ getMultiplier: jest.fn(),
+ getFiles: jest.fn(),
+ getMessages: jest.fn(),
+ getRoleByName: jest.fn(),
+ getUserMemories: jest.fn(),
+ getFormattedMemories: jest.fn(),
+ isAgentTriggerPrincipalActive: jest.fn().mockResolvedValue(true),
+ spendStructuredTokens: jest.fn(),
+ spendTokens: jest.fn(),
+ updateBalance: jest.fn(),
+}));
+jest.mock('~/config', () => ({
+ getMCPManager: jest.fn(() => ({ formatInstructionsForContext: mockFormatInstructions })),
+}));
+
+const { Constants, ContentTypes, EModelEndpoint } = require('librechat-data-provider');
+const { getMessages } = require('~/models');
+const AgentClient = require('../client');
+const { applyRetainedAnswers, GenerationJobManager } = jest.requireActual('@librechat/api');
+const { formatAgentMessages } = jest.requireActual('@librechat/agents');
+
+async function buildPrompt(client, rows, parent) {
+ const built = await client.buildMessages(rows, parent, {});
+ const formatted = formatAgentMessages(built.prompt, client.indexTokenCountMap);
+ const applied = applyRetainedAnswers({
+ block: client.retainedAnswers?.block,
+ ...formatted,
+ tokenCounter: mockCountFormattedMessageTokens,
+ });
+ return {
+ ...built,
+ prompt: applied.messages,
+ counts: applied.indexTokenCountMap,
+ memoryMessages: formatted.messages,
+ };
+}
+
+const ANSWER_LINE = 'Q: Which environment should I deploy to?\nA: staging';
+const LATEST_TEXT = 'what is next?';
+
+function askPart(request, output, id) {
+ return {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id,
+ name: 'ask_user_question',
+ args: JSON.stringify(request),
+ output,
+ progress: 1,
+ },
+ };
+}
+
+/** The text a formatted message carries, whether its content is a string or parts. */
+function contentText(message) {
+ const content = message?.content;
+ if (typeof content === 'string') {
+ return content;
+ }
+ return (content ?? [])
+ .filter((part) => part?.type === ContentTypes.TEXT)
+ .map((part) => part.text)
+ .join('\n');
+}
+
+function latestUserMessage() {
+ return {
+ messageId: 'u3',
+ parentMessageId: 'a2',
+ sender: 'User',
+ text: LATEST_TEXT,
+ isCreatedByUser: true,
+ };
+}
+
+/**
+ * A branch whose answered question sits BEFORE a checkpoint summary: the prompt
+ * builder's history walk stops at the summary, so the model no longer sees the
+ * message that carried the answer.
+ */
+function compactedBranch() {
+ return [
+ {
+ messageId: 'u1',
+ parentMessageId: Constants.NO_PARENT,
+ sender: 'User',
+ text: 'deploy the app',
+ isCreatedByUser: true,
+ },
+ {
+ messageId: 'a1',
+ parentMessageId: 'u1',
+ sender: 'Agent',
+ isCreatedByUser: false,
+ content: [
+ { type: ContentTypes.TEXT, text: 'Let me check.' },
+ askPart(
+ { questions: [{ id: 'environment', question: 'Which environment should I deploy to?' }] },
+ JSON.stringify({ answers: { environment: 'staging' } }),
+ 'tc-1',
+ ),
+ ],
+ },
+ {
+ messageId: 'u2',
+ parentMessageId: 'a1',
+ sender: 'User',
+ text: 'go on',
+ isCreatedByUser: true,
+ },
+ {
+ messageId: 'a2',
+ parentMessageId: 'u2',
+ sender: 'Agent',
+ isCreatedByUser: false,
+ content: [
+ { type: ContentTypes.SUMMARY, text: 'Earlier context, compacted.', tokenCount: 5 },
+ { type: ContentTypes.TEXT, text: 'Deployed.' },
+ ],
+ },
+ latestUserMessage(),
+ ];
+}
+
+function makeClient(agentsConfig = {}) {
+ const client = new AgentClient({
+ req: {
+ user: { id: 'user-123' },
+ body: { endpoint: EModelEndpoint.agents },
+ config: { endpoints: { [EModelEndpoint.agents]: agentsConfig } },
+ },
+ res: {},
+ agent: {
+ id: 'agent-123',
+ endpoint: EModelEndpoint.openAI,
+ provider: EModelEndpoint.openAI,
+ instructions: 'Base agent instructions',
+ model_parameters: { model: 'gpt-4' },
+ tools: [],
+ },
+ endpoint: EModelEndpoint.agents,
+ endpointTokenConfig: {},
+ eventHandlers: {},
+ contentParts: [],
+ collectedUsage: [],
+ artifactPromises: [],
+ });
+ client.conversationId = 'convo-123';
+ client.responseMessageId = 'response-123';
+ client.shouldSummarize = true;
+ client.maxContextTokens = 4096;
+ client.recordCollectedUsage = jest.fn().mockResolvedValue();
+ return client;
+}
+
+describe('AgentClient retained answers', () => {
+ afterAll(async () => {
+ await GenerationJobManager.destroy();
+ });
+
+ const ROW_QUERY = [
+ { conversationId: 'convo-123', user: 'user-123' },
+ 'messageId parentMessageId content isCreatedByUser isUserSubmitted userSubmittedPaths userSubmittedMessageFieldPaths',
+ ];
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockFormatInstructions.mockResolvedValue('');
+ getMessages.mockResolvedValue([]);
+ });
+
+ it('completes the branch the history read cut at the summary and quotes the answer in the user turn', async () => {
+ const client = makeClient();
+ client.user = 'user-123';
+ client.processMemory = jest.fn();
+ const rows = compactedBranch();
+ getMessages.mockResolvedValue(rows);
+ /** The real loader: one read of the conversation, then the summary-bounded walk. */
+ const cut = await client.loadHistory('convo-123', 'u3');
+ expect(cut.map((message) => message.messageId)).toEqual(['a2', 'u3']);
+ expect(getMessages).toHaveBeenCalledTimes(1);
+ expect(client.loadedHistoryRows).toBe(rows);
+
+ const { prompt, tokenCountMap, counts, memoryMessages } = await buildPrompt(client, cut, 'u3');
+
+ expect(getMessages).toHaveBeenCalledTimes(1);
+ expect(client.loadedHistoryRows).toBeUndefined();
+ expect(JSON.stringify(memoryMessages)).not.toContain(ANSWER_LINE);
+ const text = prompt.map(contentText).join('\n');
+ expect(text).toContain(ANSWER_LINE);
+ expect(text.indexOf(ANSWER_LINE)).toBeLessThan(text.indexOf(LATEST_TEXT));
+ expect(text.endsWith(LATEST_TEXT)).toBe(true);
+ expect(client.options.agent.additional_instructions ?? '').not.toContain(ANSWER_LINE);
+ expect(cut[1].text).toBe(LATEST_TEXT);
+ expect(cut[1].content).toBeUndefined();
+ expect(counts[prompt.length - 1]).toBe(tokenCountMap.u3);
+ expect(contentText(memoryMessages[memoryMessages.length - 1])).not.toContain(ANSWER_LINE);
+ });
+
+ it.each(['cold', 'warm'])(
+ 'delivers the block through %s chatCompletion while memory receives the unmodified SDK transcript',
+ async (continuation) => {
+ const client = makeClient();
+ client.processMemory = jest.fn();
+ client.runMemory = jest.fn().mockResolvedValue();
+ client.user = 'user-123';
+ getMessages.mockResolvedValue(compactedBranch());
+ const cut = await client.loadHistory('convo-123', 'u3');
+ const built = await client.buildMessages(cut, 'u3', {});
+ client.eventActorContinuation = continuation;
+ mockFormatAgentMessages.mockImplementationOnce(formatAgentMessages);
+ const processStream = jest.fn().mockResolvedValue();
+ mockCreateRun.mockResolvedValueOnce({
+ Graph: null,
+ graphRunnable: { getState: jest.fn().mockResolvedValue({ values: { messages: [] } }) },
+ processStream,
+ getCalibrationRatio: jest.fn(() => 0),
+ getInterrupt: jest.fn(() => undefined),
+ });
+
+ await client.chatCompletion({ payload: built.prompt });
+
+ expect(mockCreateRun).toHaveBeenCalledTimes(1);
+ const input = mockCreateRun.mock.calls[0][0];
+ expect(input.messages.map(contentText).join('\n')).toContain(ANSWER_LINE);
+ expect(mockRuntimeCounter).toHaveBeenCalledTimes(1);
+ expect(input.tokenCounter).toBe(mockRuntimeCounter.mock.results[0].value);
+ if (continuation === 'warm') {
+ expect(input.indexTokenCountMap).toEqual({});
+ expect(
+ input.tokenCounter(
+ input.messages.find((message) => message.id === 'librechat:retained-answers'),
+ ),
+ ).toBeGreaterThan(0);
+ } else {
+ expect(input.indexTokenCountMap[input.messages.length - 1]).toBe(built.tokenCountMap.u3);
+ }
+ expect(client.runMemory).toHaveBeenCalledTimes(1);
+ expect(contentText(client.runMemory.mock.calls[0][0].at(-1))).not.toContain(ANSWER_LINE);
+ expect(client.memoryPayload).toBeNull();
+ expect(processStream).toHaveBeenCalledTimes(1);
+ expect(processStream.mock.calls[0][0].messages.map(contentText).join('\n')).toContain(
+ ANSWER_LINE,
+ );
+ },
+ );
+
+ it('passes the retained-aware runtime counter to checkpoint resumes', async () => {
+ const client = makeClient();
+ const job = await GenerationJobManager.createJob('convo-123', 'user-123', 'convo-123');
+ client.jobCreatedAt = job.createdAt;
+ const counter = jest.fn(() => 123);
+ mockRuntimeCounter.mockReturnValueOnce(counter);
+ const resume = jest.fn().mockResolvedValue();
+ mockCreateRun.mockResolvedValueOnce({
+ Graph: null,
+ resume,
+ processStream: jest.fn().mockResolvedValue(),
+ getCalibrationRatio: jest.fn(() => 0),
+ getInterrupt: jest.fn(() => undefined),
+ });
+
+ await client.resumeCompletion({
+ resumeValue: { answer: 'staging' },
+ streamId: 'convo-123',
+ checkpointNamespace: 'retained-counter',
+ });
+
+ expect(mockRuntimeCounter).toHaveBeenCalledTimes(1);
+ expect(mockCreateRun.mock.calls[0][0]).toEqual(
+ expect.objectContaining({ messages: [], tokenCounter: counter }),
+ );
+ expect(resume).toHaveBeenCalledTimes(1);
+ });
+
+ it('reads nothing when the rows in memory already reach the branch root', async () => {
+ const client = makeClient();
+ client.shouldSummarize = false;
+ const rows = compactedBranch();
+ rows[3].content = [{ type: ContentTypes.TEXT, text: 'Deployed.' }];
+
+ const { prompt } = await buildPrompt(client, rows, 'u3');
+
+ expect(getMessages).not.toHaveBeenCalled();
+ expect(
+ contentText(prompt.find((message) => message.id === 'librechat:retained-answers')),
+ ).toContain(ANSWER_LINE);
+ });
+
+ it('leaves the turn alone when the operator turned retained answers off', async () => {
+ const client = makeClient({ askUserQuestion: { retainedAnswers: { enabled: false } } });
+
+ const { prompt } = await buildPrompt(client, compactedBranch(), 'u3');
+
+ expect(getMessages).not.toHaveBeenCalled();
+ expect(contentText(prompt[prompt.length - 1])).toBe(LATEST_TEXT);
+ expect(client.memoryPayload).toBeNull();
+ });
+
+ it('reads the stored branch for a warm event-actor turn that skipped history', async () => {
+ const client = makeClient();
+ client.eventActorContinuation = 'warm';
+ getMessages.mockResolvedValue(compactedBranch());
+
+ const { prompt } = await buildPrompt(client, [latestUserMessage()], 'u3');
+
+ expect(getMessages).toHaveBeenCalledWith(...ROW_QUERY);
+ expect(
+ contentText(prompt.find((message) => message.id === 'librechat:retained-answers')),
+ ).toContain(ANSWER_LINE);
+ });
+
+ it('leaves an array-form user row and its memory copy untouched', async () => {
+ const client = makeClient();
+ client.shouldSummarize = false;
+ client.processMemory = jest.fn();
+ const rows = compactedBranch();
+ rows[3].content = [{ type: ContentTypes.TEXT, text: 'Deployed.' }];
+ const shared = [{ type: ContentTypes.TEXT, text: LATEST_TEXT }];
+ rows[4] = { ...rows[4], text: undefined, content: shared };
+
+ const { prompt, memoryMessages } = await buildPrompt(client, rows, 'u3');
+
+ expect(
+ contentText(prompt.find((message) => message.id === 'librechat:retained-answers')),
+ ).toContain(ANSWER_LINE);
+ expect(shared).toEqual([{ type: ContentTypes.TEXT, text: LATEST_TEXT }]);
+ expect(rows[4].content).toBe(shared);
+ expect(contentText(memoryMessages[memoryMessages.length - 1])).toBe(LATEST_TEXT);
+ });
+
+ it('measures the block against a fresh count even when the stored count was calibrated', async () => {
+ const client = makeClient();
+ client.shouldSummarize = false;
+ const rows = compactedBranch();
+ rows[3].content = [{ type: ContentTypes.TEXT, text: 'Deployed.' }];
+ rows[4].tokenCount = 5000;
+
+ const { prompt, tokenCountMap, counts } = await buildPrompt(client, rows, 'u3');
+
+ expect(tokenCountMap.u3).toBe(5000);
+ const blockOnly = mockCountFormattedMessageTokens({
+ role: 'user',
+ content: [{ type: ContentTypes.TEXT, text: ANSWER_LINE }],
+ });
+ expect(counts[prompt.length - 1]).toBe(5000);
+ expect(
+ counts[prompt.findIndex((message) => message.id === 'librechat:retained-answers')],
+ ).toBeGreaterThanOrEqual(blockOnly);
+ });
+
+ it('builds no memory copy when memory processing is inactive', async () => {
+ const client = makeClient();
+ client.shouldSummarize = false;
+ const rows = compactedBranch();
+ rows[3].content = [{ type: ContentTypes.TEXT, text: 'Deployed.' }];
+
+ const { prompt } = await buildPrompt(client, rows, 'u3');
+
+ expect(
+ contentText(prompt.find((message) => message.id === 'librechat:retained-answers')),
+ ).toContain(ANSWER_LINE);
+ expect(client.memoryPayload).toBeNull();
+ });
+
+ it('quotes into the turn being continued when the leaf is the unfinished response', async () => {
+ const client = makeClient();
+ client.shouldSummarize = false;
+ const rows = compactedBranch();
+ rows[3].content = [{ type: ContentTypes.TEXT, text: 'Deployed.' }];
+ rows.push({
+ messageId: 'a3',
+ parentMessageId: 'u3',
+ sender: 'Agent',
+ isCreatedByUser: false,
+ content: [{ type: ContentTypes.TEXT, text: 'Next I will' }],
+ unfinished: true,
+ });
+
+ const { prompt } = await buildPrompt(client, rows, 'a3');
+
+ expect(prompt[prompt.length - 1].getType()).toBe('ai');
+ expect(
+ contentText(prompt.find((message) => message.id === 'librechat:retained-answers')),
+ ).toContain(ANSWER_LINE);
+ expect(contentText(prompt[prompt.length - 1])).not.toContain(ANSWER_LINE);
+ });
+});
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js
index 0176ad23ce..c98ec0c583 100644
--- a/api/server/controllers/agents/client.js
+++ b/api/server/controllers/agents/client.js
@@ -74,6 +74,11 @@ const {
checkpointOwnerNamespacePrefix,
isAskUserQuestionAdminDisabled,
attachAskUserQuestionArgs,
+ prepareRetainedAnswers,
+ withRetainedAnswerTokenCounter,
+ applyRetainedAnswers,
+ prepareRetainedAnswerInvocationMessages,
+ resolveRetainedAnswersConfig,
hydrateResumeRunSteps,
createContentIndexOffsetHandlers,
createSteerIndexOffsetHandlers,
@@ -2189,6 +2194,7 @@ class AgentClient extends BaseClient {
agents: this.eventActorAgentContextSources ?? agents,
invokedSkills: skillManifest,
approvalPolicy: agentsConfig?.toolApproval,
+ retainedAnswers: resolveRetainedAnswersConfig(agentsConfig?.askUserQuestion),
memory,
discoveredToolNames,
checkpointerType: agentsConfig?.checkpointer?.type,
@@ -2251,6 +2257,12 @@ class AgentClient extends BaseClient {
void this.publishRunContextMeta?.();
}
+ /** Every row `loadHistory` read this turn, held only until the retained
+ * answers are built: the walk it returns stops at a checkpoint summary. */
+ onHistoryLoaded(rows) {
+ this.loadedHistoryRows = rows;
+ }
+
async loadHistory(conversationId, parentMessageId = null) {
if (this.eventActorContinuation === 'warm') {
logger.debug('[AgentClient] Skipping durable history for compatible event actor', {
@@ -2277,6 +2289,26 @@ class AgentClient extends BaseClient {
mapMethod: createMultiAgentMapper(this.options.agent, this.agentConfigs),
mapCondition: (message) => message.addedConvo === true,
});
+ /**
+ * Answers the user gave to earlier `ask_user_question` calls. Read from the
+ * rows before `messages` is narrowed to `orderedMessages`; when those rows
+ * stop short of the branch root (the history read stopped at a checkpoint
+ * summary, or a warm event-actor turn holds only its new event message) the
+ * module completes the branch from the rows that read already fetched, or
+ * through the stored-row query when there was no read. Rendered here,
+ * applied after SDK summary slicing in chatCompletion.
+ */
+ const retainedAnswersPromise = prepareRetainedAnswers({
+ messages,
+ parentMessageId,
+ storedRows: this.loadedHistoryRows,
+ getMessages: db.getMessages,
+ conversationId: this.conversationId,
+ userId: this.user ?? this.options.req.user?.id,
+ config: this.options.req.config?.endpoints?.[EModelEndpoint.agents]?.askUserQuestion,
+ encoding: this.getEncoding(),
+ });
+ this.loadedHistoryRows = undefined;
let payload;
/** @type {number | undefined} */
@@ -2816,6 +2848,9 @@ class AgentClient extends BaseClient {
agentScopedContextPromise,
]);
+ this.retainedAnswers = await retainedAnswersPromise;
+ promptTokens += this.retainedAnswers.tokenCount;
+
/** Augmented prompt from RAG/context handlers */
this.augmentedPrompt = augmentedPrompt;
if (this.augmentedPrompt) {
@@ -4527,7 +4562,10 @@ class AgentClient extends BaseClient {
this.options.subagentTasks == null ? undefined : [Constants.CHECK_BACKGROUND_TASK],
payload,
);
- const tokenCounter = await createCachedTokenCounter(this.getEncoding());
+ const tokenCounter = withRetainedAnswerTokenCounter(
+ await createCachedTokenCounter(this.getEncoding()),
+ this.getEncoding(),
+ );
/** Pre-resolve invoked skill bodies + re-prime files before formatting messages */
if (this.eventActorContinuation === 'cold') {
@@ -4716,6 +4754,14 @@ class AgentClient extends BaseClient {
tokenCounter,
});
+ const memorySourceMessages = initialMessages;
+ ({ messages: initialMessages, indexTokenCountMap } = applyRetainedAnswers({
+ block: this.retainedAnswers?.block,
+ messages: initialMessages,
+ indexTokenCountMap,
+ tokenCounter,
+ }));
+
const memoryMessages =
this.processMemory && this.memoryPayload && !isCompactionTurn
? formatAgentMessages(
@@ -4725,7 +4771,7 @@ class AgentClient extends BaseClient {
skillPrimeResult?.skills,
hasMessageFormatOptions ? messageFormatOptions : undefined,
).messages
- : initialMessages;
+ : memorySourceMessages;
/**
* @param {BaseMessage[]} messages
@@ -4967,8 +5013,11 @@ class AgentClient extends BaseClient {
/** The inherited tier must be on the job before any Stop can read it. */
await this.publishRunContextMeta?.();
try {
- const invocationMessages =
- this.eventActorContinuation === 'warm' ? messages.slice(-1) : messages;
+ const invocationMessages = await prepareRetainedAnswerInvocationMessages(
+ messages,
+ this.eventActorContinuation === 'warm',
+ () => run.graphRunnable.getState(config),
+ );
await run.processStream({ messages: invocationMessages }, config, {
callbacks: {
[Callback.TOOL_ERROR]: logToolError,
@@ -5312,7 +5361,10 @@ class AgentClient extends BaseClient {
this.contentParts.push(...seedContent);
}
- const tokenCounter = await createCachedTokenCounter(this.getEncoding());
+ const tokenCounter = withRetainedAnswerTokenCounter(
+ await createCachedTokenCounter(this.getEncoding()),
+ this.getEncoding(),
+ );
this.compactionSemanticIndexSnapshot =
restoreCompactionSemanticIndexSnapshot(compactionSemanticIndex);
const agents = collectReachableAgents([
diff --git a/librechat.example.yaml b/librechat.example.yaml
index dc77303721..681057eabb 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -718,6 +718,12 @@ endpoints:
# checkpointer:
# type: mongo # mongo (default) or memory (single-process development only)
# ttl: 86400 # Approval window in seconds; defaults to 24 hours
+ # # (optional) Keep the user's answers to Ask User questions in the model context verbatim,
+ # # even after the messages that carried them were summarized or pruned. On by default.
+ # askUserQuestion:
+ # retainedAnswers:
+ # enabled: true
+ # maxTokens: 4096 # Older answers drop first past this budget; the newest is always kept
# # (optional) Authenticate machine clients for the Agent Management API.
# # Each verified OAuth client is bound server-side to one existing LibreChat
# # user and tenant; that user's normal role and Agent ACLs still apply.
diff --git a/packages/api/src/agents/client.spec.ts b/packages/api/src/agents/client.spec.ts
index 77dbea864a..97700e4492 100644
--- a/packages/api/src/agents/client.spec.ts
+++ b/packages/api/src/agents/client.spec.ts
@@ -230,6 +230,22 @@ describe('prependFileContext', () => {
]);
});
+ it('replaces array content instead of editing the array the stored row shares', () => {
+ const shared = [
+ { type: ContentTypes.TEXT, text: 'Answer this question.' },
+ { type: ContentTypes.IMAGE_URL, image_url: { url: 'data:image/png;base64,AAA' } },
+ ];
+ const message: FormattedMessageWithContent = { content: shared };
+ prependFileContext(message, 'Attached file text');
+ expect(shared[0]).toEqual({ type: ContentTypes.TEXT, text: 'Answer this question.' });
+ expect(message.content).not.toBe(shared);
+ if (!Array.isArray(message.content)) {
+ throw new Error('Expected array content');
+ }
+ expect(message.content[0].text).toBe('Attached file text\nAnswer this question.');
+ expect(message.content[1]).toBe(shared[1]);
+ });
+
it('leaves content unchanged when file context is empty', () => {
const message: FormattedMessageWithContent = { content: 'Answer this question.' };
diff --git a/packages/api/src/agents/client.ts b/packages/api/src/agents/client.ts
index 2a644b27e9..4b05d2b8e7 100644
--- a/packages/api/src/agents/client.ts
+++ b/packages/api/src/agents/client.ts
@@ -106,16 +106,24 @@ export function applyAttachmentOnlyText(
formattedMessage.content = ATTACHMENT_ONLY_TEXT;
}
-export function prependFileContext(
+/**
+ * Prepends context text to a formatted message: joined ahead of its string
+ * content or first text part, or added as a leading text part when it has
+ * neither. Array content is replaced, never edited in place: a formatted copy
+ * shares its array with the stored row it came from, so the stored row and
+ * every other reader of it stay untouched.
+ */
+export function prependContextText(
formattedMessage: FormattedMessageWithContent,
- fileContext?: string | null,
+ text: string | null | undefined,
+ separator = '\n',
): void {
- if (!fileContext) {
+ if (!text) {
return;
}
if (typeof formattedMessage.content === 'string') {
- formattedMessage.content = `${fileContext}\n${formattedMessage.content}`;
+ formattedMessage.content = `${text}${separator}${formattedMessage.content}`;
return;
}
@@ -123,13 +131,24 @@ export function prependFileContext(
return;
}
- const textPart = formattedMessage.content.find((part) => part.type === ContentTypes.TEXT);
- if (textPart != null && typeof textPart.text === 'string') {
- textPart.text = `${fileContext}\n${textPart.text}`;
+ const index = formattedMessage.content.findIndex(
+ (part) => part.type === ContentTypes.TEXT && typeof part.text === 'string',
+ );
+ if (index < 0) {
+ formattedMessage.content = [{ type: ContentTypes.TEXT, text }, ...formattedMessage.content];
return;
}
+ const textPart = formattedMessage.content[index];
+ formattedMessage.content = formattedMessage.content.map((part, position) =>
+ position === index ? { ...textPart, text: `${text}${separator}${textPart.text}` } : part,
+ );
+}
- formattedMessage.content.unshift({ type: ContentTypes.TEXT, text: fileContext });
+export function prependFileContext(
+ formattedMessage: FormattedMessageWithContent,
+ fileContext?: string | null,
+): void {
+ prependContextText(formattedMessage, fileContext);
}
/**
diff --git a/packages/api/src/agents/compatibility.spec.ts b/packages/api/src/agents/compatibility.spec.ts
index 991062ea54..e36b680fe0 100644
--- a/packages/api/src/agents/compatibility.spec.ts
+++ b/packages/api/src/agents/compatibility.spec.ts
@@ -263,3 +263,28 @@ describe('event actor summary state', () => {
);
});
});
+
+describe('retained-answer checkpoint compatibility', () => {
+ it('rebuilds warm state after enabling, disabling, changing the budget, or upgrading legacy context', () => {
+ const base = { agents: [{ id: 'agent-1' }] };
+ const enabled = createInitializedAgentContextFingerprint({
+ ...base,
+ retainedAnswers: { enabled: true, maxTokens: 4096 },
+ });
+ for (const retainedAnswers of [
+ undefined,
+ { enabled: false, maxTokens: 4096 },
+ { enabled: true, maxTokens: 1024 },
+ ]) {
+ expect(
+ createInitializedAgentContextFingerprint({ ...base, retainedAnswers }).digest,
+ ).not.toBe(enabled.digest);
+ }
+ expect(
+ createInitializedAgentContextFingerprint({
+ ...base,
+ retainedAnswers: { enabled: true, maxTokens: 4096 },
+ }).digest,
+ ).toBe(enabled.digest);
+ });
+});
diff --git a/packages/api/src/agents/compatibility.ts b/packages/api/src/agents/compatibility.ts
index f0e5662375..48e58de70e 100644
--- a/packages/api/src/agents/compatibility.ts
+++ b/packages/api/src/agents/compatibility.ts
@@ -48,6 +48,7 @@ export interface AgentContextDefinition {
export interface AgentTurnSemanticContext {
agents: readonly AgentContextDefinition[];
approvalPolicy?: object;
+ retainedAnswers?: { enabled: boolean; maxTokens: number };
memory?: readonly AgentContextMemorySnapshot[];
checkpointerType?: string;
discoveredToolNames?: readonly string[];
@@ -251,6 +252,7 @@ export function createAgentContextFingerprint(
checkpointerType: input.checkpointerType,
discoveredToolNames: normalizeAgentEventActorDiscoveredTools(input.discoveredToolNames),
approvalPolicy: input.approvalPolicy,
+ retainedAnswers: input.retainedAnswers,
agents: input.agents.map((agent) => ({
...agent,
modelParameters: redactModelParameterCredentials(agent.modelParameters),
@@ -300,6 +302,7 @@ export function createInitializedAgentContextFingerprint(input: {
agents: readonly InitializedAgentContextSource[];
invokedSkills?: readonly AgentContextSkillIdentity[];
approvalPolicy?: object;
+ retainedAnswers?: { enabled: boolean; maxTokens: number };
memory?: readonly AgentContextMemorySnapshot[];
checkpointerType?: string;
discoveredToolNames?: readonly string[];
@@ -307,6 +310,7 @@ export function createInitializedAgentContextFingerprint(input: {
return createAgentContextFingerprint({
checkpointerType: input.checkpointerType,
approvalPolicy: input.approvalPolicy,
+ retainedAnswers: input.retainedAnswers,
memory: input.memory,
discoveredToolNames: input.discoveredToolNames,
agents: input.agents.map((agent, index) => ({
diff --git a/packages/api/src/agents/hitl/answers.spec.ts b/packages/api/src/agents/hitl/answers.spec.ts
new file mode 100644
index 0000000000..9cd0aa876d
--- /dev/null
+++ b/packages/api/src/agents/hitl/answers.spec.ts
@@ -0,0 +1,1003 @@
+import { Constants, ContentTypes, DEFAULT_RETAINED_ANSWER_TOKENS } from 'librechat-data-provider';
+import {
+ formatAgentMessages,
+ messagesStateReducer,
+ getMessagesWithinTokenLimit,
+} from '@librechat/agents';
+import {
+ HumanMessage,
+ AIMessage,
+ ToolMessage,
+ SystemMessage,
+ mapStoredMessagesToChatMessages,
+ mapChatMessagesToStoredMessages,
+} from '@librechat/agents/langchain/messages';
+import {
+ applyRetainedAnswers,
+ prepareRetainedAnswerInvocationMessages,
+ RETAINED_ANSWERS_MESSAGE_ID,
+ buildRetainedAnswersContext,
+ collectRetainedAnswers,
+ orderConversationBranch,
+ reachesBranchRoot,
+ renderRetainedAnswers,
+ resolveRetainedAnswersConfig,
+ RETAINED_ANSWER_ROW_FIELDS,
+ prepareRetainedAnswers,
+ withRetainedAnswerTokenCounter,
+} from './answers';
+import { countFormattedMessageTokens, createCachedTokenCounter } from '../client';
+import { attachAskUserQuestionAnswers } from './resume';
+import Tokenizer from '~/utils/tokenizer';
+
+const mockWarn = jest.fn();
+jest.mock('@librechat/data-schemas', () => ({
+ logger: {
+ warn: (...args: unknown[]) => mockWarn(...args),
+ debug: jest.fn(),
+ error: jest.fn(),
+ info: jest.fn(),
+ },
+}));
+
+const ASK = 'ask_user_question';
+const NO_PARENT: string = Constants.NO_PARENT;
+
+const countChars = (text: string): number => text.length;
+
+function askPart(args: unknown, output: unknown, id = 'tc-1') {
+ return {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id,
+ name: ASK,
+ args: typeof args === 'string' ? args : JSON.stringify(args),
+ output,
+ progress: 1,
+ inputValidationError: undefined as true | undefined,
+ },
+ };
+}
+
+const batchRequest = {
+ questions: [
+ { id: 'environment', question: 'Which environment should I deploy to?' },
+ { id: 'window', question: 'Which time window?', header: 'Window' },
+ ],
+};
+
+describe('collectRetainedAnswers', () => {
+ test('maps a batched answer set onto its questions in question order', () => {
+ const sets = collectRetainedAnswers([
+ {
+ content: [
+ { type: ContentTypes.TEXT, text: 'Let me check.' },
+ askPart(
+ batchRequest,
+ JSON.stringify({ answers: { window: 'last 7 days', environment: 'staging' } }),
+ ),
+ ],
+ },
+ ]);
+
+ expect(sets).toEqual([
+ {
+ toolCallId: 'tc-1',
+ answers: [
+ { question: 'Which environment should I deploy to?', answer: 'staging' },
+ { question: 'Which time window?', answer: 'last 7 days' },
+ ],
+ },
+ ]);
+ });
+
+ test('keeps a question whose answer is missing out of the set without dropping the rest', () => {
+ const sets = collectRetainedAnswers([
+ { content: [askPart(batchRequest, JSON.stringify({ answers: { window: 'last 7 days' } }))] },
+ ]);
+ expect(sets[0].answers).toEqual([{ question: 'Which time window?', answer: 'last 7 days' }]);
+ });
+
+ test('quotes a legacy single-question answer exactly as typed, JSON-looking or not', () => {
+ const legacy = { question: 'What should I name the file?' };
+ const sets = collectRetainedAnswers([
+ { content: [askPart(legacy, 'notes.md', 'tc-a')] },
+ { content: [askPart(legacy, '{"answer":"yes","reason":"it is late"}', 'tc-b')] },
+ { content: [askPart(legacy, '{"answers":{"x":"y"}}', 'tc-c')] },
+ ]);
+ expect(sets.map((set) => set.answers[0].answer)).toEqual([
+ 'notes.md',
+ '{"answer":"yes","reason":"it is late"}',
+ '{"answers":{"x":"y"}}',
+ ]);
+ });
+
+ test('reads a pause record whose stored args are the bare question string', () => {
+ const sets = collectRetainedAnswers([
+ { content: [askPart('"What should I name the file?"', 'notes.md', 'tc-s')] },
+ ]);
+ expect(sets).toEqual([
+ {
+ toolCallId: 'tc-s',
+ answers: [{ question: 'What should I name the file?', answer: 'notes.md' }],
+ },
+ ]);
+ });
+
+ test('skips a call whose input failed validation, whose output is the error', () => {
+ const failed = askPart(
+ { question: 'Deploy where?' },
+ 'Option labels must be 280 characters or fewer.',
+ 'tc-f',
+ );
+ failed.tool_call.inputValidationError = true;
+ expect(collectRetainedAnswers([{ content: [failed] }])).toEqual([]);
+ });
+
+ test('ignores other tools, unanswered asks, and malformed stamps', () => {
+ const sets = collectRetainedAnswers([
+ {
+ content: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: { id: 'x', name: 'lookup', args: '{}', output: 'ok' },
+ },
+ askPart(batchRequest, ''),
+ askPart(batchRequest, undefined, 'tc-2'),
+ askPart('not json', JSON.stringify({ answers: { environment: 'staging' } }), 'tc-3'),
+ askPart(batchRequest, 'plain text for a two-question batch', 'tc-4'),
+ {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: { id: 'tc-5', name: ASK, args: '{}', output: 'x' },
+ },
+ ],
+ },
+ { content: 'not an array' },
+ null as never,
+ ]);
+ expect(sets).toEqual([]);
+ });
+
+ test('keeps every answered call, even when a provider reuses a tool-call id across rows', () => {
+ const sets = collectRetainedAnswers([
+ {
+ content: [
+ askPart(batchRequest, JSON.stringify({ answers: { environment: 'staging' } }), 'call_0'),
+ ],
+ },
+ { content: [askPart({ question: 'Other?' }, 'later', 'call_1')] },
+ { content: [askPart({ question: 'Ship it?' }, 'yes', 'call_0')] },
+ ]);
+ expect(sets.map((set) => set.answers[0].answer)).toEqual(['staging', 'later', 'yes']);
+ });
+});
+
+describe('orderConversationBranch', () => {
+ const rows = [
+ { messageId: 'root', parentMessageId: NO_PARENT },
+ { messageId: 'a1', parentMessageId: 'root' },
+ { messageId: 'u2', parentMessageId: 'a1' },
+ { messageId: 'a2', parentMessageId: 'u2' },
+ { messageId: 'u2-alt', parentMessageId: 'a1' },
+ { messageId: 'a2-alt', parentMessageId: 'u2-alt' },
+ ];
+
+ test('walks parents from the leaf and returns only that branch, oldest first', () => {
+ expect(orderConversationBranch(rows, 'a2').map((row) => row.messageId)).toEqual([
+ 'root',
+ 'a1',
+ 'u2',
+ 'a2',
+ ]);
+ expect(orderConversationBranch(rows, 'a2-alt').map((row) => row.messageId)).toEqual([
+ 'root',
+ 'a1',
+ 'u2-alt',
+ 'a2-alt',
+ ]);
+ });
+
+ test('returns nothing for no parent, an unknown parent, and stops on a cycle', () => {
+ expect(orderConversationBranch(rows, NO_PARENT)).toEqual([]);
+ expect(orderConversationBranch(rows, null)).toEqual([]);
+ expect(orderConversationBranch(rows, 'missing')).toEqual([]);
+ const cyclic = [
+ { messageId: 'x', parentMessageId: 'y' },
+ { messageId: 'y', parentMessageId: 'x' },
+ ];
+ expect(orderConversationBranch(cyclic, 'x').map((row) => row.messageId)).toEqual(['y', 'x']);
+ });
+
+ test('keeps the first row seen for an id, so the caller decides which rows win', () => {
+ const memory = { messageId: 'u2', parentMessageId: 'a1', content: 'memory' };
+ const loaded = { messageId: 'u2', parentMessageId: 'a1', content: 'loaded' };
+ const branch: Array<{ messageId: string; parentMessageId: string; content?: string }> = [
+ memory,
+ ...rows,
+ loaded,
+ ];
+ expect(orderConversationBranch(branch, 'u2').map((row) => row.content)).toEqual([
+ undefined,
+ undefined,
+ 'memory',
+ ]);
+ });
+
+ test('reachesBranchRoot tells a whole branch from one cut short of its root', () => {
+ expect(reachesBranchRoot([])).toBe(false);
+ expect(reachesBranchRoot([{ messageId: 'r', parentMessageId: NO_PARENT }])).toBe(true);
+ expect(reachesBranchRoot([{ messageId: 'r', parentMessageId: null }])).toBe(true);
+ expect(reachesBranchRoot([{ messageId: 'r', parentMessageId: '' }])).toBe(true);
+ expect(reachesBranchRoot([{ messageId: 'a2', parentMessageId: 'u2' }])).toBe(false);
+ });
+});
+
+describe('renderRetainedAnswers', () => {
+ const sets = [
+ { toolCallId: 'tc-1', answers: [{ question: 'First?', answer: 'one' }] },
+ {
+ toolCallId: 'tc-2',
+ answers: [
+ { question: 'Second?', answer: 'two' },
+ { question: 'Third?', answer: 'three' },
+ ],
+ },
+ { toolCallId: 'tc-3', answers: [{ question: 'Fourth?', answer: 'four' }] },
+ ];
+
+ test('renders every answer oldest first under the header when the budget allows', async () => {
+ const text = await renderRetainedAnswers(sets, 10_000, countChars);
+ expect(text).toContain(
+ '# Answers the user gave to questions asked earlier in this conversation',
+ );
+ expect(text).toContain('Q: First?\nA: one');
+ expect(text).toContain('Q: Second?\nA: two\n\nQ: Third?\nA: three');
+ expect(text?.indexOf('First?')).toBeLessThan(text?.indexOf('Fourth?') ?? -1);
+ expect(text).not.toContain('omitted');
+ });
+
+ test('drops the oldest sets first once the budget is exceeded and says how many answers went', async () => {
+ const newest = (await renderRetainedAnswers([sets[2]], 10_000, countChars)) as string;
+ const text = (await renderRetainedAnswers(sets, newest.length + 5, countChars)) as string;
+ expect(text).toContain('Q: Fourth?\nA: four');
+ expect(text).not.toContain('Second?');
+ expect(text).toContain('(3 earlier answers omitted');
+ });
+
+ test('budgets the separators and the note, so many tiny sets still fit the ceiling', async () => {
+ const tiny = Array.from({ length: 60 }, (_, index) => ({
+ toolCallId: `tc-${index}`,
+ answers: [{ question: 'Q?', answer: 'y' }],
+ }));
+ const newest = (await renderRetainedAnswers([tiny[59]], 10_000, countChars)) as string;
+ const maxTokens = newest.length + 120;
+ const text = (await renderRetainedAnswers(tiny, maxTokens, countChars)) as string;
+ expect(text.length).toBeLessThanOrEqual(maxTokens);
+ expect(text).toContain('earlier answers omitted');
+ expect(text.endsWith('Q: Q?\nA: y')).toBe(true);
+ });
+
+ test('does not reserve the omission note when every set fits without it', async () => {
+ const full = (await renderRetainedAnswers(sets, 10_000, countChars)) as string;
+ expect(full).not.toContain('omitted');
+ const exact = (await renderRetainedAnswers(sets, full.length, countChars)) as string;
+ expect(exact).toBe(full);
+ const short = (await renderRetainedAnswers(sets, full.length - 1, countChars)) as string;
+ expect(short).toContain('omitted');
+ expect(short).not.toContain('First?');
+ });
+
+ test('always keeps the newest set even when it alone exceeds the budget', async () => {
+ const text = (await renderRetainedAnswers(sets, 1, countChars)) as string;
+ expect(text).toContain('Q: Fourth?\nA: four');
+ expect(text).not.toContain('First?');
+ });
+
+ test('measures whole blocks when the tokenizer charges per-message overhead', async () => {
+ const framed = (text: string) => text.length + 10;
+ const full = (await renderRetainedAnswers(sets, 10_000, framed)) as string;
+ expect(await renderRetainedAnswers(sets, framed(full), framed)).toBe(full);
+ });
+
+ test('stops tokenizing old answers once the retained suffix fills the budget', async () => {
+ const history = Array.from({ length: 10_000 }, (_, index) => ({
+ answers: [{ question: `Q${index}?`, answer: 'yes' }],
+ }));
+ const counter = jest.fn(countChars);
+ const text = await renderRetainedAnswers(history, 600, counter);
+ expect(text).toContain('Q9999?');
+ expect(text?.length).toBeLessThanOrEqual(600);
+ expect(counter.mock.calls.length).toBeLessThan(30);
+ });
+
+ test('does not claim omissions when the only set exceeds the budget', async () => {
+ expect(await renderRetainedAnswers([sets[0]], 1, countChars)).not.toContain('omitted');
+ });
+
+ test.each(['o200k_base', 'claude'] as const)(
+ 'fits the final rendered block with the real %s tokenizer',
+ async (encoding) => {
+ const history = Array.from({ length: 100 }, (_, index) => ({
+ answers: [
+ {
+ question: `Choose ${index}: café or 東京?`,
+ answer: '東京 — keep the original wording.',
+ },
+ ],
+ }));
+ const counter = (text: string) =>
+ countFormattedMessageTokens({ role: 'user', content: text }, encoding) ?? 0;
+ const full = (await renderRetainedAnswers(history, 100_000, counter)) as string;
+ expect(await renderRetainedAnswers(history, counter(full), counter)).toBe(full);
+ const limited = (await renderRetainedAnswers(history, 300, counter)) as string;
+ expect(counter(limited)).toBeGreaterThan(0);
+ expect(counter(limited)).toBeLessThanOrEqual(300);
+ expect(limited).toContain('Choose 99');
+ },
+ );
+
+ test('returns undefined for no sets', async () => {
+ expect(await renderRetainedAnswers([], 100, countChars)).toBeUndefined();
+ });
+});
+
+describe('resolveRetainedAnswersConfig', () => {
+ test('is on with the default budget when nothing is configured', () => {
+ expect(resolveRetainedAnswersConfig(undefined)).toEqual({
+ enabled: true,
+ maxTokens: DEFAULT_RETAINED_ANSWER_TOKENS,
+ });
+ expect(resolveRetainedAnswersConfig({})).toEqual({
+ enabled: true,
+ maxTokens: DEFAULT_RETAINED_ANSWER_TOKENS,
+ });
+ });
+
+ test('honors an explicit off switch and a positive integer budget', () => {
+ expect(resolveRetainedAnswersConfig({ retainedAnswers: { enabled: false } }).enabled).toBe(
+ false,
+ );
+ expect(resolveRetainedAnswersConfig({ retainedAnswers: { maxTokens: 512.9 } }).maxTokens).toBe(
+ 512,
+ );
+ });
+
+ test('falls back to the default for a budget that reaches runtime unvalidated', () => {
+ for (const maxTokens of [0, 0.5, -1, Number.NaN, Number.POSITIVE_INFINITY, '2048', null]) {
+ expect(
+ resolveRetainedAnswersConfig({ retainedAnswers: { maxTokens: maxTokens as never } })
+ .maxTokens,
+ ).toBe(DEFAULT_RETAINED_ANSWER_TOKENS);
+ }
+ });
+});
+
+describe('buildRetainedAnswersContext', () => {
+ const answered = askPart(batchRequest, JSON.stringify({ answers: { environment: 'staging' } }));
+ const summary = {
+ type: ContentTypes.SUMMARY,
+ text: 'Earlier context, compacted.',
+ tokenCount: 5,
+ };
+ const rows = [
+ { messageId: 'u1', parentMessageId: NO_PARENT, content: [{ type: 'text', text: 'deploy' }] },
+ { messageId: 'a1', parentMessageId: 'u1', content: [answered] },
+ { messageId: 'u2', parentMessageId: 'a1', content: [{ type: 'text', text: 'go on' }] },
+ { messageId: 'a2', parentMessageId: 'u2', content: [summary, { type: 'text', text: 'done' }] },
+ { messageId: 'u3', parentMessageId: 'a2', content: [{ type: 'text', text: 'next' }] },
+ ];
+ const ANSWER_LINE = 'Q: Which environment should I deploy to?\nA: staging';
+
+ beforeEach(() => {
+ mockWarn.mockClear();
+ });
+
+ test('carries an answer given before a checkpoint summary', async () => {
+ const text = await buildRetainedAnswersContext({
+ messages: rows,
+ parentMessageId: 'u3',
+ config: undefined,
+ countTokens: countChars,
+ });
+ expect(text).toContain(ANSWER_LINE);
+ });
+
+ test('reads only the branch that ends at the parent', async () => {
+ const text = await buildRetainedAnswersContext({
+ messages: [...rows, { messageId: 'u1-alt', parentMessageId: NO_PARENT, content: [] }],
+ parentMessageId: 'u1-alt',
+ config: undefined,
+ countTokens: countChars,
+ });
+ expect(text).toBeUndefined();
+ });
+
+ test('yields nothing when disabled or when no answer exists', async () => {
+ expect(
+ await buildRetainedAnswersContext({
+ messages: rows,
+ parentMessageId: 'u3',
+ config: { retainedAnswers: { enabled: false } },
+ countTokens: countChars,
+ }),
+ ).toBeUndefined();
+ expect(
+ await buildRetainedAnswersContext({
+ messages: rows,
+ parentMessageId: 'u1',
+ config: undefined,
+ countTokens: countChars,
+ }),
+ ).toBeUndefined();
+ });
+
+ test('completes a branch cut short of its root through the injected query', async () => {
+ const getMessages = jest.fn(async () => rows);
+ const cut = [
+ { ...rows[3], content: [{ type: 'text', text: 'Earlier context, compacted.' }] },
+ rows[4],
+ ];
+ const text = await buildRetainedAnswersContext({
+ messages: cut,
+ parentMessageId: 'u3',
+ getMessages,
+ conversationId: 'convo-1',
+ userId: 'user-1',
+ config: undefined,
+ countTokens: countChars,
+ });
+ expect(text).toContain(ANSWER_LINE);
+ expect(getMessages).toHaveBeenCalledWith(
+ { conversationId: 'convo-1', user: 'user-1' },
+ RETAINED_ANSWER_ROW_FIELDS,
+ );
+ expect(RETAINED_ANSWER_ROW_FIELDS).toContain(
+ 'isUserSubmitted userSubmittedPaths userSubmittedMessageFieldPaths',
+ );
+ });
+
+ test('completes the branch from the rows the turn already read instead of querying again', async () => {
+ const getMessages = jest.fn(async () => rows);
+ const cut = [
+ { ...rows[3], content: [{ type: 'text', text: 'Earlier context, compacted.' }] },
+ rows[4],
+ ];
+ const text = await buildRetainedAnswersContext({
+ messages: cut,
+ parentMessageId: 'u3',
+ storedRows: rows,
+ getMessages,
+ conversationId: 'convo-1',
+ userId: 'user-1',
+ config: undefined,
+ countTokens: countChars,
+ });
+ expect(text).toContain(ANSWER_LINE);
+ expect(getMessages).not.toHaveBeenCalled();
+ });
+
+ test('completes a lone event message the same way', async () => {
+ const getMessages = jest.fn(async () => rows);
+ const text = await buildRetainedAnswersContext({
+ messages: [rows[4]],
+ parentMessageId: 'u3',
+ getMessages,
+ conversationId: 'convo-1',
+ userId: 'user-1',
+ config: undefined,
+ countTokens: countChars,
+ });
+ expect(text).toContain(ANSWER_LINE);
+ expect(getMessages).toHaveBeenCalledTimes(1);
+ });
+
+ test('never queries when the rows in memory reach the root or retention is off', async () => {
+ const getMessages = jest.fn(async () => rows);
+ const whole = await buildRetainedAnswersContext({
+ messages: rows,
+ parentMessageId: 'u3',
+ getMessages,
+ conversationId: 'convo-1',
+ userId: 'user-1',
+ config: undefined,
+ countTokens: countChars,
+ });
+ expect(whole).toContain(ANSWER_LINE);
+ await buildRetainedAnswersContext({
+ messages: [rows[4]],
+ parentMessageId: 'u3',
+ getMessages,
+ conversationId: 'convo-1',
+ userId: 'user-1',
+ config: { retainedAnswers: { enabled: false } },
+ countTokens: countChars,
+ });
+ expect(getMessages).not.toHaveBeenCalled();
+ });
+
+ test('lets a stored row outrank the prompt-shaped copy in memory', async () => {
+ const withAsk = {
+ messageId: 'a2',
+ parentMessageId: 'u2',
+ content: [summary, askPart({ question: 'Ship it?' }, 'yes', 'tc-a2')],
+ };
+ const shaped = { ...withAsk, content: [{ type: 'text', text: 'Earlier context, compacted.' }] };
+ const text = await buildRetainedAnswersContext({
+ messages: [shaped, rows[4]],
+ parentMessageId: 'u3',
+ getMessages: async () => [rows[0], rows[1], rows[2], withAsk],
+ conversationId: 'convo-1',
+ userId: 'user-1',
+ config: undefined,
+ countTokens: countChars,
+ });
+ expect(text).toContain(ANSWER_LINE);
+ expect(text).toContain('Q: Ship it?\nA: yes');
+ });
+
+ test('uses canonical stored answers even when a mapped branch still reaches its root', async () => {
+ const mapped = rows.map((row) => (row.messageId === 'a1' ? { ...row, content: [] } : row));
+ const query = jest.fn();
+ const text = await buildRetainedAnswersContext({
+ messages: mapped,
+ storedRows: rows,
+ parentMessageId: 'u3',
+ getMessages: query,
+ config: undefined,
+ countTokens: countChars,
+ });
+ expect(text).toContain(ANSWER_LINE);
+ expect(query).not.toHaveBeenCalled();
+ });
+
+ test('carries what is in memory and warns when the stored rows cannot be read', async () => {
+ const inMemory = [
+ { messageId: 'a9', parentMessageId: 'u9', content: [askPart({ question: 'Ok?' }, 'yes')] },
+ { messageId: 'u10', parentMessageId: 'a9', content: [] },
+ ];
+ const text = await buildRetainedAnswersContext({
+ messages: inMemory,
+ parentMessageId: 'u10',
+ getMessages: async () => {
+ throw new Error('rows unavailable');
+ },
+ conversationId: 'convo-1',
+ userId: 'user-1',
+ config: undefined,
+ countTokens: countChars,
+ });
+ expect(text).toContain('Q: Ok?\nA: yes');
+ expect(mockWarn).toHaveBeenCalledTimes(1);
+ });
+
+ test('never rejects: a failing counter costs the turn its block, not the turn', async () => {
+ const text = await buildRetainedAnswersContext({
+ messages: rows,
+ parentMessageId: 'u3',
+ config: undefined,
+ countTokens: () => {
+ throw new Error('tokenizer down');
+ },
+ });
+ expect(text).toBeUndefined();
+ expect(mockWarn).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('applyRetainedAnswers', () => {
+ const block = '# Answers\n\nQ: Deploy where?\nA: staging';
+ const tokenCounter = (message: { content: unknown }) => JSON.stringify(message.content).length;
+
+ test('adds dedicated context and preserves user messages and calibrated counts', () => {
+ const user = new HumanMessage({ content: [{ type: 'text', text: 'go on' }], id: 'user-1' });
+ const assistant = new AIMessage('unfinished');
+ const messages = [user, assistant];
+ const counts = { 0: 5000, 1: 12 };
+ const result = applyRetainedAnswers({
+ block,
+ messages,
+ indexTokenCountMap: counts,
+ tokenCounter,
+ });
+ expect(result.messages[0].content).toBe(block);
+ expect(result.messages[0].id).toBe(RETAINED_ANSWERS_MESSAGE_ID);
+ expect(result.messages[1]).toBe(user);
+ expect(result.messages[2]).toBe(assistant);
+ expect(user.content).toEqual([{ type: 'text', text: 'go on' }]);
+ expect(counts).toEqual({ 0: 5000, 1: 12 });
+ expect(result.indexTokenCountMap).toEqual({
+ 0: tokenCounter(result.messages[0]),
+ 1: 5000,
+ 2: 12,
+ });
+ });
+
+ test('survives real summary slicing with no human turn left and preserves the continuation', () => {
+ const payload = [
+ { role: 'user', content: 'earlier user' },
+ {
+ role: 'assistant',
+ content: [
+ { type: 'summary', text: 'Summary', tokenCount: 5 },
+ { type: 'text', text: 'unfinished' },
+ ],
+ },
+ ];
+ const formatted = formatAgentMessages(payload, { 0: 20, 1: 30 });
+ expect(formatted.messages.every((message) => message.getType() !== 'human')).toBe(true);
+ const result = applyRetainedAnswers({ block, ...formatted, tokenCounter });
+ expect(result.messages.map((message) => message.getType())).toEqual(['human', 'ai']);
+ expect(result.messages[0].content).toBe(block);
+ expect(result.messages[1]).toBe(formatted.messages[0]);
+ expect(result.indexTokenCountMap[1]).toBe(formatted.indexTokenCountMap?.[0]);
+ expect(result.indexTokenCountMap[0]).toBe(tokenCounter(result.messages[0]));
+ expect(formatted.messages).toHaveLength(1);
+ });
+
+ test.each([
+ { isMeta: true, source: 'skill' },
+ { source: 'skill' },
+ { source: 'handoff' },
+ { source: 'hook' },
+ { source: 'system' },
+ { injected: true },
+ { role: 'system' },
+ ])('keeps retained user context outside synthetic messages: %j', (additional_kwargs) => {
+ const prime = new HumanMessage({ content: 'skill instructions', additional_kwargs });
+ const continuation = new AIMessage('unfinished');
+ for (const hasUser of [false, true]) {
+ const messages = hasUser
+ ? [new HumanMessage('continue'), prime, continuation]
+ : [prime, continuation];
+ const result = applyRetainedAnswers({ block, messages, tokenCounter });
+ expect(result.messages[0].getType()).toBe('human');
+ expect(result.messages[0].content).toContain(block);
+ expect(result.messages[0].additional_kwargs).toEqual({
+ librechat_retained_answers: block,
+ });
+ expect(result.messages.slice(1)).toEqual(messages);
+ expect(prime.content).toBe('skill instructions');
+ }
+ });
+
+ test('keeps a legacy system summary first when adding context to a continuation', () => {
+ const messages = [new SystemMessage('Summary'), new AIMessage('unfinished')];
+ const result = applyRetainedAnswers({
+ block,
+ messages,
+ indexTokenCountMap: { 0: 10, 1: 20 },
+ tokenCounter,
+ });
+ expect(result.messages.map((message) => message.getType())).toEqual(['system', 'human', 'ai']);
+ expect(result.indexTokenCountMap).toEqual({
+ 0: 10,
+ 1: tokenCounter(result.messages[1]),
+ 2: 20,
+ });
+ });
+
+ test('keeps tool-call/result adjacency when summary replay has no human message', () => {
+ const messages = [
+ new AIMessage({ content: '', tool_calls: [{ id: 'call', name: 'lookup', args: {} }] }),
+ new ToolMessage({ content: 'result', tool_call_id: 'call' }),
+ new AIMessage('unfinished'),
+ ];
+ const result = applyRetainedAnswers({
+ block,
+ messages,
+ indexTokenCountMap: { 0: 10, 1: 20, 2: 30 },
+ tokenCounter,
+ });
+ expect(result.messages.slice(1)).toEqual(messages);
+ expect(result.indexTokenCountMap).toEqual({
+ 0: tokenCounter(result.messages[0]),
+ 1: 10,
+ 2: 20,
+ 3: 30,
+ });
+ });
+
+ test.each(['throw', 'nan', 'undefined'])(
+ 'leaves the memory transcript and counts untouched on counter failure: %s',
+ (failure) => {
+ const messages = [new HumanMessage('go on')];
+ const counts = { 0: 8 };
+ const result = applyRetainedAnswers({
+ block,
+ messages,
+ indexTokenCountMap: counts,
+ tokenCounter: () => {
+ if (failure === 'throw') throw new Error('counter unavailable');
+ return failure === 'nan' ? Number.NaN : (undefined as never);
+ },
+ });
+ expect(result.messages).toBe(messages);
+ expect(result.indexTokenCountMap).toBe(counts);
+ expect(messages[0].content).toBe('go on');
+ },
+ );
+
+ test('uses a fresh baseline when the formatted token map has no entry', () => {
+ const result = applyRetainedAnswers({
+ block,
+ messages: [new HumanMessage('go on')],
+ indexTokenCountMap: {},
+ tokenCounter,
+ });
+ expect(result.indexTokenCountMap[0]).toBe(tokenCounter(result.messages[0]));
+ });
+
+ test('does no work when there is no block', () => {
+ const messages = [new HumanMessage('go on')];
+ const counts = { 0: 8 };
+ const counter = jest.fn();
+ expect(
+ applyRetainedAnswers({
+ block: undefined,
+ messages,
+ indexTokenCountMap: counts,
+ tokenCounter: counter,
+ }),
+ ).toEqual({ messages, indexTokenCountMap: counts });
+ expect(counter).not.toHaveBeenCalled();
+ });
+});
+
+describe('retained answer lifecycle', () => {
+ test('refreshes retained context at the newest position over repeated serialized warm checkpoint turns', async () => {
+ let checkpoint: ReturnType<typeof messagesStateReducer> = [];
+ const counter = (message: { content: unknown }) => String(message.content).length;
+ for (let turn = 0; turn < 50; turn++) {
+ const event = new HumanMessage({ id: `event-${turn}`, content: `event ${turn}` });
+ const block = `answers for turn ${turn}`;
+ const prepared = applyRetainedAnswers({ block, messages: [event], tokenCounter: counter });
+ const invocation = await prepareRetainedAnswerInvocationMessages(
+ prepared.messages,
+ turn > 0,
+ async () => ({ values: { messages: checkpoint } }),
+ );
+ checkpoint = messagesStateReducer(checkpoint, invocation);
+ checkpoint = mapStoredMessagesToChatMessages(
+ JSON.parse(JSON.stringify(mapChatMessagesToStoredMessages(checkpoint))),
+ );
+ const retained = checkpoint.filter((message) => message.id === RETAINED_ANSWERS_MESSAGE_ID);
+ expect(retained).toHaveLength(1);
+ expect(retained[0].content).toBe(block);
+ expect(checkpoint[checkpoint.length - 2]).toBe(retained[0]);
+ const pruned = getMessagesWithinTokenLimit({
+ messages: checkpoint,
+ maxContextTokens: counter(retained[0]) + counter(event) + 3,
+ indexTokenCountMap: Object.fromEntries(
+ checkpoint.map((message, index) => [index, counter(message)]),
+ ),
+ tokenCounter: counter,
+ });
+ expect(pruned.context.map((message) => message.content)).toContain(block);
+ if (turn > 1) expect(pruned.context.length).toBeLessThan(checkpoint.length);
+ expect(checkpoint.filter((message) => message.id?.startsWith('event-'))).toHaveLength(
+ turn + 1,
+ );
+ }
+ });
+
+ test('does not read cold/no-answer state and preserves warm state after read failure', async () => {
+ const event = new HumanMessage({ id: 'event', content: 'event' });
+ const read = jest.fn().mockRejectedValue(new Error('checkpoint unavailable'));
+ expect(await prepareRetainedAnswerInvocationMessages([event], false, read)).toEqual([event]);
+ expect(await prepareRetainedAnswerInvocationMessages([event], true, read)).toEqual([event]);
+ expect(read).not.toHaveBeenCalled();
+ const prepared = applyRetainedAnswers({
+ block: 'answers',
+ messages: [event],
+ tokenCounter: () => 10,
+ });
+ expect(await prepareRetainedAnswerInvocationMessages(prepared.messages, true, read)).toEqual([
+ event,
+ ]);
+ expect(read).toHaveBeenCalledTimes(1);
+ expect(
+ await prepareRetainedAnswerInvocationMessages(prepared.messages, true, async () => ({
+ values: {},
+ })),
+ ).toEqual([event]);
+ });
+
+ test('preserves checkpoint tool pairs and deduplicates a retried event during relocation', async () => {
+ const event = new HumanMessage({ id: 'event', content: 'event' });
+ const toolPair = [
+ new AIMessage({
+ id: 'call-message',
+ content: '',
+ tool_calls: [{ id: 'call', name: 'lookup', args: {} }],
+ }),
+ new ToolMessage({ id: 'result', content: 'result', tool_call_id: 'call' }),
+ ];
+ const prepared = applyRetainedAnswers({
+ block: 'answers',
+ messages: [event],
+ tokenCounter: () => 10,
+ });
+ const history = [...prepared.messages, ...toolPair];
+ const invocation = await prepareRetainedAnswerInvocationMessages(
+ prepared.messages,
+ true,
+ async () => ({ values: { messages: history } }),
+ );
+ expect(messagesStateReducer(history, invocation)).toEqual([...toolPair, ...prepared.messages]);
+ expect(history).toEqual([...prepared.messages, ...toolPair]);
+ });
+
+ test('rejects imported and caller-authored stamps while preserving exact HITL answer provenance', () => {
+ const content = [askPart({ question: 'Where?' }, 'staging')];
+ expect(collectRetainedAnswers([{ content, isUserSubmitted: true }])).toEqual([]);
+ expect(collectRetainedAnswers([{ content, isCreatedByUser: true }])).toEqual([]);
+ for (const path of [
+ '/content',
+ '/content/0',
+ '/content/0/tool_call/name',
+ '/content/0/tool_call/args',
+ '/content/0/tool_call/output',
+ ]) {
+ expect(collectRetainedAnswers([{ content, userSubmittedPaths: [path] }])).toEqual([]);
+ }
+ expect(
+ collectRetainedAnswers([
+ {
+ content,
+ isCreatedByUser: false,
+ userSubmittedPaths: ['/content/0/tool_call/output'],
+ userSubmittedMessageFieldPaths: [
+ { path: '/content/0/tool_call/output', field: 'answer' },
+ ],
+ },
+ ]),
+ ).toHaveLength(1);
+ expect(collectRetainedAnswers([{ content }])).toHaveLength(1);
+ });
+
+ test('exact-counts only marked retained text across serialization and merged large content', async () => {
+ const prepared = await prepareRetainedAnswers({
+ messages: [
+ {
+ messageId: 'a',
+ parentMessageId: NO_PARENT,
+ content: [askPart({ question: 'Where?' }, 'staging')],
+ },
+ ],
+ parentMessageId: 'a',
+ config: undefined,
+ });
+ const fallback = jest.fn(await createCachedTokenCounter('o200k_base'));
+ const counter = withRetainedAnswerTokenCounter(fallback, 'o200k_base');
+ const large = 'large ordinary paste '.repeat(100000);
+ const exact = jest.spyOn(Tokenizer, 'countExactTokens');
+ try {
+ const applied = applyRetainedAnswers({
+ block: prepared.block,
+ messages: [new HumanMessage(large)],
+ tokenCounter: counter,
+ });
+ const restored = mapStoredMessagesToChatMessages(
+ JSON.parse(JSON.stringify(mapChatMessagesToStoredMessages(applied.messages))),
+ );
+ const originalCount = counter(restored[0]);
+ expect(originalCount).toBe(applied.indexTokenCountMap[0]);
+ expect(exact.mock.calls.every(([text]) => text.length < 4096)).toBe(true);
+ expect(counter(new HumanMessage(String(restored[0].content)))).toBe(
+ fallback(new HumanMessage(String(restored[0].content))),
+ );
+ const merged = new HumanMessage({
+ ...restored[0],
+ content: [
+ { type: 'text', text: 'merged prefix' },
+ { type: 'text', text: String(restored[0].content) },
+ ],
+ });
+ expect(counter(merged)).toBeGreaterThanOrEqual(originalCount);
+ expect(exact.mock.calls.every(([text]) => text.length < 4096)).toBe(true);
+ const changed = new HumanMessage({ ...restored[0], content: 'redacted content' });
+ expect(counter(changed)).toBe(fallback(changed));
+ } finally {
+ exact.mockRestore();
+ }
+ });
+
+ test('preserves the fallback counter for ordinary content with empty parts', () => {
+ const message = new HumanMessage({
+ content: [null as never, { type: 'text', text: 'ordinary' }],
+ });
+ const fallback = jest.fn(() => 12);
+ expect(withRetainedAnswerTokenCounter(fallback, 'o200k_base')(message)).toBe(12);
+ expect(fallback).toHaveBeenCalledWith(message);
+ });
+
+ test.each(['o200k_base', 'claude'] as const)(
+ 'retains a block over 4 KiB that fits the actual %s token budget',
+ async (encoding) => {
+ const content = Array.from({ length: 100 }, (_, index) =>
+ askPart(
+ { question: `Question ${index}: which environment should receive the next deployment?` },
+ 'Use staging and keep the existing configuration unchanged.',
+ `call-${index}`,
+ ),
+ );
+ const prepared = await prepareRetainedAnswers({
+ messages: [{ messageId: 'answer', parentMessageId: NO_PARENT, content }],
+ parentMessageId: 'answer',
+ config: { retainedAnswers: { maxTokens: 4096 } },
+ encoding,
+ });
+ expect(prepared.block?.length).toBeGreaterThan(4096);
+ expect(prepared.block).toContain('Question 0:');
+ expect(prepared.block).toContain('Question 99:');
+ expect(prepared.block).not.toContain('omitted');
+ expect(prepared.tokenCount).toBeLessThanOrEqual(4096);
+ const fallback = jest.fn(await createCachedTokenCounter(encoding));
+ const tokenCounter = withRetainedAnswerTokenCounter(fallback, encoding);
+ const messages = [new HumanMessage('Continue.')];
+ const result = applyRetainedAnswers({
+ block: prepared.block,
+ messages,
+ indexTokenCountMap: { 0: tokenCounter(messages[0]) },
+ tokenCounter,
+ });
+ expect(result.indexTokenCountMap[0]).toBe(tokenCounter(result.messages[0]));
+ expect(result.indexTokenCountMap[0]).toBeLessThan(4200);
+ const runtimeCounter = withRetainedAnswerTokenCounter(fallback, encoding);
+ const restored = mapStoredMessagesToChatMessages(
+ JSON.parse(JSON.stringify(mapChatMessagesToStoredMessages(result.messages))),
+ );
+ expect(runtimeCounter(restored[0])).toBe(result.indexTokenCountMap[0]);
+ const ordinary = new HumanMessage('unrelated large input '.repeat(1000));
+ expect(runtimeCounter(ordinary)).toBe(fallback(ordinary));
+ const tool = new ToolMessage({ content: prepared.block ?? '', tool_call_id: 'call' });
+ expect(runtimeCounter(tool)).toBe(fallback(tool));
+ },
+ );
+
+ test('carries durable resume stamps after reconstruction, summary slicing, and a second turn without duplication', async () => {
+ const request = { questions: [{ id: 'env', question: 'Deploy where?' }] };
+ const stamped = attachAskUserQuestionAnswers(
+ [askPart(request, undefined)],
+ [{ toolCallId: 'tc-1', request, output: JSON.stringify({ answers: { env: 'staging' } }) }],
+ );
+ const rows = JSON.parse(
+ JSON.stringify([
+ { messageId: 'u1', parentMessageId: NO_PARENT, content: [] },
+ { messageId: 'a1', parentMessageId: 'u1', content: stamped },
+ {
+ messageId: 'a2',
+ parentMessageId: 'a1',
+ content: [
+ { type: 'summary', text: 'Summary', tokenCount: 5 },
+ { type: 'text', text: 'unfinished' },
+ ],
+ },
+ ]),
+ );
+ const prepared = await prepareRetainedAnswers({
+ messages: [rows[2]],
+ storedRows: rows,
+ parentMessageId: 'a2',
+ config: undefined,
+ countTokens: countChars,
+ });
+ expect(prepared.block).toContain('Q: Deploy where?\nA: staging');
+ expect(prepared.tokenCount).toBe(prepared.block?.length);
+ const original = formatAgentMessages([{ role: 'assistant', content: rows[2].content }], {
+ 0: 50,
+ });
+ for (let turn = 0; turn < 2; turn++) {
+ const result = applyRetainedAnswers({
+ block: prepared.block,
+ ...original,
+ tokenCounter: (message) => JSON.stringify(message.content).length,
+ });
+ expect(
+ JSON.stringify(result.messages.map((message) => message.content)).match(/Deploy where/g),
+ ).toHaveLength(1);
+ expect(original.messages).toHaveLength(1);
+ expect(JSON.stringify(rows[2])).not.toContain('Deploy where');
+ }
+ });
+});
diff --git a/packages/api/src/agents/hitl/answers.ts b/packages/api/src/agents/hitl/answers.ts
new file mode 100644
index 0000000000..e4b2e67e67
--- /dev/null
+++ b/packages/api/src/agents/hitl/answers.ts
@@ -0,0 +1,699 @@
+import { logger } from '@librechat/data-schemas';
+import { BaseMessage, HumanMessage } from '@librechat/agents/langchain/messages';
+import { Constants, ContentTypes, DEFAULT_RETAINED_ANSWER_TOKENS } from 'librechat-data-provider';
+import {
+ withMessageRole,
+ getTokenCountForMessage,
+ createRemoveAllMessage,
+} from '@librechat/agents';
+import type { TAskUserQuestionConfig } from 'librechat-data-provider';
+import type { TokenCounter } from '@librechat/agents';
+import type { EncodingName } from '~/utils/tokenizer';
+import { ASK_USER_QUESTION_TOOL_NAME } from './askUserQuestionTool';
+import { CLAUDE_TOKEN_CORRECTION } from '../client';
+import { getSafeErrorMetadata } from '~/utils';
+import Tokenizer from '~/utils/tokenizer';
+
+/** The projection a stored-row loader needs; nothing else is read. */
+export const RETAINED_ANSWER_ROW_FIELDS =
+ 'messageId parentMessageId content isCreatedByUser isUserSubmitted userSubmittedPaths userSubmittedMessageFieldPaths';
+
+/** Identifies the one retained-context message when relocating warm checkpoint history. */
+export const RETAINED_ANSWERS_MESSAGE_ID = 'librechat:retained-answers';
+
+/** The fields the scan reads from a stored row or an in-memory message. */
+export interface RetainedAnswerSource {
+ messageId?: string | null;
+ parentMessageId?: string | null;
+ content?: unknown;
+ isCreatedByUser?: boolean;
+ isUserSubmitted?: boolean;
+ userSubmittedPaths?: readonly string[];
+ userSubmittedMessageFieldPaths?: readonly { path: string; field: string }[];
+}
+
+export interface RetainedAnswer {
+ question: string;
+ answer: string;
+}
+
+/** The answers one `ask_user_question` call received, in question order. */
+export interface RetainedAnswerSet {
+ toolCallId?: string;
+ answers: RetainedAnswer[];
+}
+
+export interface RetainedAnswersConfig {
+ enabled: boolean;
+ maxTokens: number;
+}
+
+export type RetainedAnswerTokenCounter = (text: string) => number | Promise<number>;
+
+/** The stored-row query, in the shape the data layer's `getMessages` already has. */
+export type RetainedAnswerRowQuery = (
+ filter: { conversationId: string; user: string },
+ select: string,
+) => Promise<readonly RetainedAnswerSource[] | null | undefined>;
+
+const SEPARATOR = '\n\n';
+
+const RETAINED_ANSWERS_HEADER = [
+ '# Answers the user gave to questions asked earlier in this conversation',
+ 'Quoted exactly as given, oldest first. They stay in force even after the messages that carried',
+ 'them were summarized or dropped; do not ask these questions again unless the user changes an answer.',
+].join('\n');
+
+interface AskToolCallPart {
+ type?: string;
+ tool_call?: {
+ id?: unknown;
+ name?: unknown;
+ args?: unknown;
+ output?: unknown;
+ inputValidationError?: unknown;
+ };
+}
+
+interface AskedQuestion {
+ id?: string;
+ question: string;
+}
+
+interface AskedRequest {
+ batched: boolean;
+ questions: AskedQuestion[];
+}
+
+function parseJsonObject(value: unknown): Record<string, unknown> | undefined {
+ if (value != null && typeof value === 'object' && !Array.isArray(value)) {
+ return value as Record<string, unknown>;
+ }
+ if (typeof value !== 'string' || value.length === 0) {
+ return undefined;
+ }
+ try {
+ const parsed: unknown = JSON.parse(value);
+ return parsed != null && typeof parsed === 'object' && !Array.isArray(parsed)
+ ? (parsed as Record<string, unknown>)
+ : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/** A stored `args` value that is a JSON-encoded string: the question itself, as
+ * pause records written before the structured request shape carried it. */
+function parseJsonString(value: unknown): string | undefined {
+ if (typeof value !== 'string' || !value.startsWith('"')) {
+ return undefined;
+ }
+ try {
+ const parsed: unknown = JSON.parse(value);
+ return typeof parsed === 'string' && parsed.length > 0 ? parsed : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/** The questions an ask call put to the user, from its stored `args`: the batched
+ * `{ questions: [...] }` shape, the legacy single `{ question }`, or the bare
+ * question string of a pause record that predates both. */
+function readRequest(args: unknown): AskedRequest | undefined {
+ const bare = parseJsonString(args);
+ if (bare != null) {
+ return { batched: false, questions: [{ question: bare }] };
+ }
+ const request = parseJsonObject(args);
+ if (request == null) {
+ return undefined;
+ }
+ if (Array.isArray(request.questions)) {
+ const questions = request.questions.flatMap((item: unknown) => {
+ const candidate = item as { id?: unknown; question?: unknown } | null;
+ if (typeof candidate?.question !== 'string' || candidate.question.length === 0) {
+ return [];
+ }
+ return [
+ {
+ ...(typeof candidate.id === 'string' && candidate.id.length > 0 && { id: candidate.id }),
+ question: candidate.question,
+ },
+ ];
+ });
+ return questions.length > 0 ? { batched: true, questions } : undefined;
+ }
+ return typeof request.question === 'string' && request.question.length > 0
+ ? { batched: false, questions: [{ question: request.question }] }
+ : undefined;
+}
+
+/**
+ * The answers stamped on an ask call's `output`. A legacy single question is
+ * stamped with the bare text the user typed, so it is quoted as is: decoding it
+ * would turn a literal `{"answer": …}` reply into something the user did not
+ * say. A batch is stamped as `{ answers: { id } }`, read by question id.
+ */
+function readAnswers(output: unknown, request: AskedRequest): RetainedAnswer[] {
+ if (typeof output !== 'string' || output.length === 0) {
+ return [];
+ }
+ if (!request.batched) {
+ return [{ question: request.questions[0].question, answer: output }];
+ }
+ const batched = parseJsonObject(output)?.answers;
+ if (batched == null || typeof batched !== 'object' || Array.isArray(batched)) {
+ return [];
+ }
+ return request.questions.flatMap(({ id, question }) => {
+ const answer = id == null ? undefined : Object.getOwnPropertyDescriptor(batched, id)?.value;
+ return typeof answer === 'string' && answer.length > 0 ? [{ question, answer }] : [];
+ });
+}
+
+/** A call whose input failed schema validation persisted the validation error
+ * as its `output`; that text is not an answer. */
+function readAskToolCall(part: unknown): RetainedAnswerSet | undefined {
+ const candidate = part as AskToolCallPart | null | undefined;
+ const toolCall = candidate?.tool_call;
+ if (
+ candidate?.type !== ContentTypes.TOOL_CALL ||
+ toolCall?.name !== ASK_USER_QUESTION_TOOL_NAME ||
+ toolCall.inputValidationError === true
+ ) {
+ return undefined;
+ }
+ const request = readRequest(toolCall.args);
+ const answers = request == null ? [] : readAnswers(toolCall.output, request);
+ if (answers.length === 0) {
+ return undefined;
+ }
+ return {
+ ...(typeof toolCall.id === 'string' && toolCall.id.length > 0 && { toolCallId: toolCall.id }),
+ answers,
+ };
+}
+
+/**
+ * Every answered `ask_user_question` call in `sources`, in the order the sources
+ * are given. Rows are already unique by message id after the branch walk, and
+ * tool-call ids are not conversation-global (a provider may reuse `call_0` on
+ * every turn), so nothing is merged across rows.
+ */
+export function collectRetainedAnswers(
+ sources: readonly RetainedAnswerSource[],
+): RetainedAnswerSet[] {
+ const sets: RetainedAnswerSet[] = [];
+ for (const source of sources) {
+ if (
+ source?.isUserSubmitted === true ||
+ source?.isCreatedByUser === true ||
+ !Array.isArray(source?.content)
+ ) {
+ continue;
+ }
+ for (const [index, part] of source.content.entries()) {
+ const root = `/content/${index}`;
+ const output = `${root}/tool_call/output`;
+ const trustedAnswer = source.userSubmittedMessageFieldPaths?.some(
+ (entry) => entry.path === output && entry.field === 'answer',
+ );
+ const callerAuthored = source.userSubmittedPaths?.some((path) => {
+ if (path === output && trustedAnswer) return false;
+ return path === '/content' || path === root || path.startsWith(`${root}/`);
+ });
+ if (callerAuthored) continue;
+ const set = readAskToolCall(part);
+ if (set != null) {
+ sets.push(set);
+ }
+ }
+ }
+ return sets;
+}
+
+/**
+ * The branch that ends at `parentMessageId`, oldest first: the walk the prompt
+ * builder makes, without its stop at a checkpoint summary. Answers given before
+ * a compaction are exactly the ones the model no longer sees. The first row
+ * seen for an id wins, so a caller puts the rows it trusts most first.
+ */
+export function orderConversationBranch<T extends RetainedAnswerSource>(
+ messages: readonly T[],
+ parentMessageId: string | null | undefined,
+): T[] {
+ if (parentMessageId == null || parentMessageId === Constants.NO_PARENT) {
+ return [];
+ }
+ const byId = new Map<string, T>();
+ for (const message of messages) {
+ const messageId = message?.messageId;
+ if (typeof messageId === 'string' && !byId.has(messageId)) {
+ byId.set(messageId, message);
+ }
+ }
+ const branch: T[] = [];
+ const visited = new Set<string>();
+ let current: string | null | undefined = parentMessageId;
+ while (typeof current === 'string' && current !== Constants.NO_PARENT && !visited.has(current)) {
+ visited.add(current);
+ const message = byId.get(current);
+ if (message == null) {
+ break;
+ }
+ branch.push(message);
+ current = message.parentMessageId;
+ }
+ return branch.reverse();
+}
+
+/**
+ * Whether an ordered branch reaches its root. The rows a turn holds in memory
+ * stop early when a checkpoint summary bounded the history read, or when a
+ * warm event-actor turn holds only its new event message; both leave the oldest
+ * row pointing at a parent that is not in memory.
+ */
+export function reachesBranchRoot(branch: readonly RetainedAnswerSource[]): boolean {
+ const root = branch[0];
+ if (root == null) {
+ return false;
+ }
+ const parent = root.parentMessageId;
+ return parent == null || parent === '' || parent === Constants.NO_PARENT;
+}
+
+function renderSet(set: RetainedAnswerSet): string {
+ return set.answers.map(({ question, answer }) => `Q: ${question}\nA: ${answer}`).join(SEPARATOR);
+}
+
+function omittedNote(count: number): string {
+ return `(${count} earlier answer${count === 1 ? '' : 's'} omitted to stay within the retained-answer budget.)`;
+}
+
+async function measureTokens(
+ text: string,
+ countTokens: RetainedAnswerTokenCounter,
+): Promise<number> {
+ const count = await countTokens(text);
+ if (!Number.isFinite(count) || count < 0) {
+ throw new Error('Invalid retained-answer token count');
+ }
+ return count;
+}
+
+/**
+ * The block quoted into the current user turn. When every set fits `maxTokens`
+ * with the header and separators, all of them are rendered oldest first.
+ * Otherwise sets are kept newest first while the block, omission note
+ * included, still fits; the newest set is always kept, the way the
+ * summarizer's recency window always keeps the latest turn.
+ */
+export async function renderRetainedAnswers(
+ sets: readonly RetainedAnswerSet[],
+ maxTokens: number,
+ countTokens: RetainedAnswerTokenCounter,
+): Promise<string | undefined> {
+ if (sets.length === 0) {
+ return undefined;
+ }
+ const newestFirst: string[] = [];
+ const answerCounts = [0];
+ const totalAnswers = sets.reduce((total, set) => total + set.answers.length, 0);
+ const candidate = (count: number, note = false): string => {
+ while (newestFirst.length < count) {
+ const set = sets[sets.length - newestFirst.length - 1];
+ newestFirst.push(renderSet(set));
+ answerCounts.push(answerCounts[answerCounts.length - 1] + set.answers.length);
+ }
+ return [
+ RETAINED_ANSWERS_HEADER,
+ ...(note ? [omittedNote(totalAnswers - answerCounts[count])] : []),
+ ...newestFirst.slice(0, count).reverse(),
+ ].join(SEPARATOR);
+ };
+ let low = 0;
+ let high = 1;
+ while ((await measureTokens(candidate(high), countTokens)) <= maxTokens) {
+ low = high;
+ if (high === sets.length) {
+ return candidate(high);
+ }
+ high = Math.min(sets.length, high * 2);
+ }
+ while (high - low > 1) {
+ const middle = Math.floor((low + high) / 2);
+ if ((await measureTokens(candidate(middle), countTokens)) <= maxTokens) {
+ low = middle;
+ } else {
+ high = middle;
+ }
+ }
+ let count = Math.max(1, low);
+ while (true) {
+ const block = candidate(count, count < sets.length);
+ if ((await measureTokens(block, countTokens)) <= maxTokens || count === 1) {
+ return block;
+ }
+ count--;
+ }
+}
+
+/** Config as the run reads it: on unless disabled, and a positive integer budget. */
+export function resolveRetainedAnswersConfig(
+ config: TAskUserQuestionConfig | null | undefined,
+): RetainedAnswersConfig {
+ const retained = config?.retainedAnswers;
+ const maxTokens = retained?.maxTokens;
+ return {
+ enabled: retained?.enabled !== false,
+ maxTokens:
+ typeof maxTokens === 'number' && Number.isFinite(maxTokens) && maxTokens >= 1
+ ? Math.floor(maxTokens)
+ : DEFAULT_RETAINED_ANSWER_TOKENS,
+ };
+}
+
+async function loadBranchRows(
+ getMessages: RetainedAnswerRowQuery,
+ conversationId: string,
+ userId: string,
+): Promise<readonly RetainedAnswerSource[]> {
+ try {
+ return (await getMessages({ conversationId, user: userId }, RETAINED_ANSWER_ROW_FIELDS)) ?? [];
+ } catch (error) {
+ logger.warn(
+ '[retainedAnswers] Stored rows unavailable; carrying only the answers already in memory',
+ getSafeErrorMetadata(error),
+ );
+ return [];
+ }
+}
+
+/** The owner-scoped read of the branch rows, when the caller supplied what it needs. */
+function resolveRowLoad(
+ getMessages: RetainedAnswerRowQuery | undefined,
+ conversationId: string | null | undefined,
+ userId: string | null | undefined,
+): (() => Promise<readonly RetainedAnswerSource[]>) | undefined {
+ if (
+ getMessages == null ||
+ typeof conversationId !== 'string' ||
+ conversationId.length === 0 ||
+ typeof userId !== 'string' ||
+ userId.length === 0
+ ) {
+ return undefined;
+ }
+ return () => loadBranchRows(getMessages, conversationId, userId);
+}
+
+export interface RetainedAnswersContextInput {
+ /** The rows in memory, which may stop short of the branch root. */
+ messages: readonly RetainedAnswerSource[];
+ parentMessageId: string | null | undefined;
+ /**
+ * Every row the turn's history read already fetched, when it made one; used
+ * to complete a branch whose rows in memory do not reach its root (a
+ * checkpoint summary bounded the walk) without reading the conversation a
+ * second time. Stored rows outrank the copies in memory, which may already be
+ * prompt-shaped.
+ */
+ storedRows?: readonly RetainedAnswerSource[] | null;
+ /**
+ * The stored-row query, for a turn that made no history read (a warm
+ * event-actor turn holds only its new event message). Called only when
+ * retention is on, the branch is incomplete and no `storedRows` were given.
+ */
+ getMessages?: RetainedAnswerRowQuery;
+ conversationId?: string | null;
+ userId?: string | null;
+ config: TAskUserQuestionConfig | null | undefined;
+ countTokens: RetainedAnswerTokenCounter;
+}
+
+async function buildContext({
+ messages,
+ parentMessageId,
+ storedRows,
+ getMessages,
+ conversationId,
+ userId,
+ config,
+ countTokens,
+}: RetainedAnswersContextInput): Promise<string | undefined> {
+ const resolved = resolveRetainedAnswersConfig(config);
+ if (!resolved.enabled) {
+ return undefined;
+ }
+ if (parentMessageId == null || parentMessageId === Constants.NO_PARENT) {
+ return undefined;
+ }
+ let branch = orderConversationBranch(
+ storedRows == null ? messages : [...storedRows, ...messages],
+ parentMessageId,
+ );
+ if (storedRows == null && !reachesBranchRoot(branch)) {
+ const load = resolveRowLoad(getMessages, conversationId, userId);
+ const stored = load == null ? undefined : await load();
+ if (stored != null) {
+ branch = orderConversationBranch([...stored, ...messages], parentMessageId);
+ }
+ }
+ const sets = collectRetainedAnswers(branch);
+ return renderRetainedAnswers(sets, resolved.maxTokens, countTokens);
+}
+
+/**
+ * The retained-answers block for one turn, or `undefined` when there is nothing
+ * to carry or the block could not be built: a failure here costs the turn its
+ * carried answers, never the turn, and is logged once per occurrence.
+ */
+export async function buildRetainedAnswersContext(
+ input: RetainedAnswersContextInput,
+): Promise<string | undefined> {
+ try {
+ return await buildContext(input);
+ } catch (error) {
+ logger.warn('[retainedAnswers] Block unavailable for this turn', getSafeErrorMetadata(error));
+ return undefined;
+ }
+}
+
+/**
+ * Exact counting is limited to retained context. The general prompt counter's
+ * 4 KiB byte-estimate shortcut would discard answers that fit the token budget.
+ * Initialize lazily so disabled retention and histories without answers cost no
+ * tokenizer load. Runtime recounts use this same exact-counting implementation.
+ */
+function countRetainedAnswerMessage(message: BaseMessage, encoding: EncodingName): number {
+ const count = getTokenCountForMessage(
+ message,
+ (text) => {
+ const tokens = Tokenizer.countExactTokens(text, encoding);
+ if (tokens == null) {
+ throw new Error('Retained-answer tokenizer unavailable');
+ }
+ return tokens;
+ },
+ encoding,
+ );
+ return encoding === 'claude' ? Math.ceil(count * CLAUDE_TOKEN_CORRECTION) : count;
+}
+
+async function createRetainedAnswerCounter(encoding: EncodingName): Promise<TokenCounter> {
+ await Tokenizer.initEncoding(encoding);
+ return (message) => countRetainedAnswerMessage(message, encoding);
+}
+
+/**
+ * The checkpoint carries the server-produced block separately from user text.
+ * Exact-count only that block; pasted/file context keeps the normal size guard.
+ * Do not mark this metadata-dependent counter content-cache-compatible: the SDK
+ * cache excludes additional_kwargs. The underlying tokenizer remains cached, and
+ * this closure retains only the most recently counted block across run recounts.
+ */
+export function withRetainedAnswerTokenCounter(
+ fallback: TokenCounter,
+ encoding: EncodingName,
+): TokenCounter {
+ let lastBlock: string | undefined;
+ let lastCount = 0;
+ return (message) => {
+ const block = message.additional_kwargs.librechat_retained_answers;
+ if (message.getType() !== 'human' || typeof block !== 'string' || !block) {
+ return fallback(message);
+ }
+ let found = false;
+ const removeBlock = (text: string): string => {
+ const index = found ? -1 : text.indexOf(block);
+ if (index < 0) return text;
+ found = true;
+ return text.slice(0, index) + text.slice(index + block.length);
+ };
+ const content = message.content;
+ let remainder = content;
+ if (typeof content === 'string') {
+ remainder = removeBlock(content);
+ } else if (Array.isArray(content)) {
+ remainder = content.map((part) =>
+ part?.type === 'text' && typeof part.text === 'string'
+ ? { ...part, text: removeBlock(part.text) }
+ : part,
+ );
+ }
+ if (!found) return fallback(message);
+ try {
+ if (block !== lastBlock) {
+ // Subtract the empty human envelope: the fallback counts it once.
+ lastCount =
+ countRetainedAnswerMessage(new HumanMessage(block), encoding) -
+ countRetainedAnswerMessage(new HumanMessage(''), encoding);
+ lastBlock = block;
+ }
+ return fallback(new HumanMessage({ ...message, content: remainder })) + lastCount;
+ } catch (error) {
+ logger.warn(
+ '[retainedAnswers] Exact recount unavailable; using the run counter',
+ getSafeErrorMetadata(error),
+ );
+ return fallback(message);
+ }
+ };
+}
+
+/** The early admission count and the block share the final prompt's exact counter. */
+export async function prepareRetainedAnswers(
+ input: Omit<RetainedAnswersContextInput, 'countTokens'> & {
+ countTokens?: RetainedAnswerTokenCounter;
+ encoding?: EncodingName;
+ },
+): Promise<{ block?: string; tokenCount: number; tokenCounter?: TokenCounter }> {
+ try {
+ let tokenCounter: TokenCounter | undefined;
+ const countTokens =
+ input.countTokens ??
+ (async (text: string) => {
+ tokenCounter ??= await createRetainedAnswerCounter(input.encoding ?? 'o200k_base');
+ return tokenCounter(new HumanMessage(text));
+ });
+ const block = await buildContext({ ...input, countTokens });
+ return {
+ block,
+ tokenCount: block == null ? 0 : await measureTokens(block, countTokens),
+ tokenCounter,
+ };
+ } catch (error) {
+ logger.warn('[retainedAnswers] Block unavailable for this turn', getSafeErrorMetadata(error));
+ return { tokenCount: 0 };
+ }
+}
+
+/**
+ * Apply after SDK summary slicing and replay. Keep a dedicated ordinary human
+ * message so neither user text nor synthetic provenance is modified. Its stable
+ * ID lets warm invocation preparation relocate the block without accumulating
+ * another copy. The caller's transcript remains unchanged for memory extraction.
+ */
+export function applyRetainedAnswers({
+ block,
+ messages,
+ indexTokenCountMap = {},
+ tokenCounter,
+}: {
+ block: string | null | undefined;
+ messages: BaseMessage[];
+ indexTokenCountMap?: Record<number, number>;
+ tokenCounter: TokenCounter;
+}): { messages: BaseMessage[]; indexTokenCountMap: Record<number, number> } {
+ const unchanged = { messages, indexTokenCountMap };
+ if (!block) return unchanged;
+ try {
+ const retained = withMessageRole(
+ new HumanMessage({
+ id: RETAINED_ANSWERS_MESSAGE_ID,
+ content: block,
+ additional_kwargs: { librechat_retained_answers: block },
+ }),
+ 'user',
+ );
+ const count = tokenCounter(retained);
+ if (!Number.isFinite(count) || count < 0)
+ throw new Error('Invalid retained-answer token count');
+ const entries = messages.flatMap((message, index) =>
+ message.id === RETAINED_ANSWERS_MESSAGE_ID
+ ? []
+ : [{ message, count: indexTokenCountMap[index] }],
+ );
+ // Place before the latest ordinary human turn, or after the system prefix
+ // when only a summary/assistant continuation survives. Never split tool pairs.
+ let insertion = entries.length - 1;
+ while (insertion >= 0) {
+ const { message } = entries[insertion];
+ if (
+ message.getType() === 'human' &&
+ message.additional_kwargs.isMeta !== true &&
+ message.additional_kwargs.injected !== true &&
+ message.additional_kwargs.source == null &&
+ message.additional_kwargs.role !== 'system'
+ )
+ break;
+ insertion--;
+ }
+ if (insertion < 0) {
+ insertion = 0;
+ while (insertion < entries.length && entries[insertion].message.getType() === 'system')
+ insertion++;
+ }
+ entries.splice(insertion, 0, { message: retained, count });
+ const counts: Record<number, number> = {};
+ entries.forEach((entry, index) => {
+ if (entry.count != null) counts[index] = entry.count;
+ });
+ return { messages: entries.map((entry) => entry.message), indexTokenCountMap: counts };
+ } catch (error) {
+ logger.warn(
+ '[retainedAnswers] Prompt unchanged after application failure',
+ getSafeErrorMetadata(error),
+ );
+ return unchanged;
+ }
+}
+
+/**
+ * Replace the message list from the exact warm checkpoint in one invocation.
+ * The SDK's ordinary ID replacement preserves the old position, so it cannot
+ * refresh recency. Its remove-all reducer command preserves the supplied
+ * transcript while moving retained context beside the new event. No checkpoint
+ * write occurs here, and cold/no-answer turns need no additional read.
+ */
+export async function prepareRetainedAnswerInvocationMessages(
+ messages: BaseMessage[],
+ warm: boolean,
+ readCheckpoint: () => Promise<{ values: unknown }>,
+): Promise<BaseMessage[]> {
+ if (!warm) return messages;
+ const latest = messages[messages.length - 1];
+ if (latest == null) return [];
+ const retained = messages.find((message) => message.id === RETAINED_ANSWERS_MESSAGE_ID);
+ if (retained == null || retained === latest) return [latest];
+ try {
+ const snapshot = await readCheckpoint();
+ const history = (snapshot.values as { messages?: unknown } | null)?.messages;
+ if (!Array.isArray(history) || !history.every(BaseMessage.isInstance)) {
+ throw new Error('Warm checkpoint messages unavailable');
+ }
+ return [
+ createRemoveAllMessage(),
+ ...history.filter(
+ (message) => message.id !== retained.id && (latest.id == null || message.id !== latest.id),
+ ),
+ retained,
+ latest,
+ ];
+ } catch (error) {
+ // Leave checkpoint state intact on read failure; never replace it with an
+ // incomplete transcript or fail the event solely for retained context.
+ logger.warn('[retainedAnswers] Warm context refresh unavailable', getSafeErrorMetadata(error));
+ return [latest];
+ }
+}
diff --git a/packages/api/src/agents/hitl/index.ts b/packages/api/src/agents/hitl/index.ts
index b5e27c03b1..2467ed756b 100644
--- a/packages/api/src/agents/hitl/index.ts
+++ b/packages/api/src/agents/hitl/index.ts
@@ -8,4 +8,5 @@ export * from './protection';
export * from './hooks';
export * from './hookLoader';
export * from './askUserQuestionTool';
+export * from './answers';
export * from './byom';
diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.ts
index 3da0959bab..d097dc6bea 100644
--- a/packages/data-provider/src/config.spec.ts
+++ b/packages/data-provider/src/config.spec.ts
@@ -2,6 +2,7 @@ import type { TEndpointsConfig } from './types';
import {
allowedAddressesSchema,
agentsEndpointSchema,
+ DEFAULT_RETAINED_ANSWER_TOKENS,
DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS,
bedrockModels,
configSchema,
@@ -23,6 +24,27 @@ const endpointsConfig: TEndpointsConfig = {
Gemini: { type: EModelEndpoint.custom, userProvide: false, order: 9999 },
};
+describe('ask user retained answers', () => {
+ it('leaves the block unconfigured by default and accepts an operator budget', () => {
+ expect(agentsEndpointSchema.parse({}).askUserQuestion).toBeUndefined();
+ expect(
+ agentsEndpointSchema.parse({
+ askUserQuestion: { retainedAnswers: { enabled: false, maxTokens: 2048 } },
+ }).askUserQuestion,
+ ).toEqual({ retainedAnswers: { enabled: false, maxTokens: 2048 } });
+ expect(DEFAULT_RETAINED_ANSWER_TOKENS).toBe(4096);
+ });
+
+ it('rejects a budget that is not a positive integer', () => {
+ for (const maxTokens of [0, -1, 1.5, '2048']) {
+ expect(
+ agentsEndpointSchema.safeParse({ askUserQuestion: { retainedAnswers: { maxTokens } } })
+ .success,
+ ).toBe(false);
+ }
+ });
+});
+
describe('retained tool-count ceiling', () => {
it('ships the exact-count budget a deployment can raise or lower', () => {
/** The save path tokenizes a stopped turn's retained tool results to add an
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index ca70c35e70..73d64858ad 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -44,6 +44,7 @@ export {
MAX_GRAPH_SUBAGENT_MEMBERS,
MAX_CHAT_PROJECT_NAME_LENGTH,
MAX_CHAT_PROJECT_DESCRIPTION_LENGTH,
+ DEFAULT_RETAINED_ANSWER_TOKENS,
DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS,
} from './limits';
@@ -1036,6 +1037,32 @@ export const toolApprovalPolicySchema = z
export type TToolApprovalPolicy = z.infer<typeof toolApprovalPolicySchema>;
+export const askUserQuestionRetainedAnswersSchema = z.object({
+ /** `false` stops carrying answers forward; they then live only in the messages. */
+ enabled: z.boolean().optional(),
+ /** Token ceiling for the carried block. Older answers drop first once it is
+ * exceeded; the newest set is always kept. Defaults to
+ * `DEFAULT_RETAINED_ANSWER_TOKENS` (4096). */
+ maxTokens: z.number().int().positive().optional(),
+});
+
+/**
+ * Behavior of the `ask_user_question` tool beyond the admin kill switch
+ * (`filteredTools` / `includedTools`).
+ *
+ * `retainedAnswers`: every answer the user gave to an agent's question is
+ * quoted verbatim in the run's user context, so it survives after the
+ * messages that carried it were summarized, pruned or dropped from the context
+ * window. On by default.
+ */
+export const askUserQuestionConfigSchema = z
+ .object({
+ retainedAnswers: askUserQuestionRetainedAnswersSchema.optional(),
+ })
+ .optional();
+
+export type TAskUserQuestionConfig = z.infer<typeof askUserQuestionConfigSchema>;
+
/**
* Durable checkpointer backing human-in-the-loop resume.
*
@@ -1421,6 +1448,8 @@ export const agentsEndpointSchema = baseEndpointSchema
remoteApi: remoteApiSchema.optional(),
/** Human-in-the-loop tool approval policy. Off by default. */
toolApproval: toolApprovalPolicySchema,
+ /** Ask User question behavior; see {@link askUserQuestionConfigSchema}. */
+ askUserQuestion: askUserQuestionConfigSchema,
/** Durable checkpointer backing tool-approval and Ask User resume.
* Defaults to the app's MongoDB when either flow needs it. */
checkpointer: checkpointerSchema,
diff --git a/packages/data-provider/src/limits.ts b/packages/data-provider/src/limits.ts
index 1c759f2efe..167deda457 100644
--- a/packages/data-provider/src/limits.ts
+++ b/packages/data-provider/src/limits.ts
@@ -33,3 +33,8 @@ export const MAX_GRAPH_SUBAGENT_MEMBERS = 32;
* context gauge can add an exact figure instead of an estimate. The schema default
* and the save path share it; tokenizing runs ~60 ms/MB, once per stopped turn. */
export const DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS = 8 * 1024 * 1024;
+
+/** Token ceiling for the block of Ask User answers carried verbatim in an agent's
+ * user context (`endpoints.agents.askUserQuestion.retainedAnswers.maxTokens`).
+ * Older answers drop first once the block exceeds it; the newest set is always kept. */
+export const DEFAULT_RETAINED_ANSWER_TOKENS = 4096;