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: ask_user_question - agent-initiated questions with durable pause/resume (#14139)

Danny Avila988a14a405e7
diff --git a/api/app/clients/tools/manifest.js b/api/app/clients/tools/manifest.js
index 302d9c3dfe..0cf1eea13e 100644
--- a/api/app/clients/tools/manifest.js
+++ b/api/app/clients/tools/manifest.js
@@ -13,8 +13,29 @@ availableTools.forEach((tool) => {
}
});
+/**
+ * Whether a tool (string pluginKey, or an OpenAI function-tool object) is
+ * flagged `agentsOnly` in the manifest — usable only on the agents runtime
+ * (e.g. `ask_user_question`, which pauses a LangGraph run via `interrupt()`).
+ * The legacy assistants runtime executes tools with no run to pause and no
+ * resume surface, so these must be rejected before assistant create/update —
+ * the tools-dialog scoping alone doesn't stop a REST client or a stale saved
+ * payload from posting the tool string directly.
+ *
+ * @param {string | { function?: { name?: string } } | undefined} tool
+ * @returns {boolean}
+ */
+function isAgentsOnlyTool(tool) {
+ const name = typeof tool === 'string' ? tool : tool?.function?.name;
+ if (!name) {
+ return false;
+ }
+ return manifestToolMap[name]?.agentsOnly === true;
+}
+
module.exports = {
toolkits,
availableTools,
manifestToolMap,
+ isAgentsOnlyTool,
};
diff --git a/api/app/clients/tools/manifest.json b/api/app/clients/tools/manifest.json
index 9637c20867..a45fca7b43 100644
--- a/api/app/clients/tools/manifest.json
+++ b/api/app/clients/tools/manifest.json
@@ -90,6 +90,13 @@
"icon": "assets/calculator.svg",
"authConfig": []
},
+ {
+ "name": "Ask User",
+ "pluginKey": "ask_user_question",
+ "description": "Let the agent pause mid-run to ask you a clarifying question and wait for your answer.",
+ "agentsOnly": true,
+ "authConfig": []
+ },
{
"name": "Stable Diffusion",
"pluginKey": "stable-diffusion",
diff --git a/api/app/clients/tools/manifest.spec.js b/api/app/clients/tools/manifest.spec.js
new file mode 100644
index 0000000000..820c3228ab
--- /dev/null
+++ b/api/app/clients/tools/manifest.spec.js
@@ -0,0 +1,22 @@
+const { manifestToolMap, isAgentsOnlyTool } = require('./manifest');
+
+describe('isAgentsOnlyTool', () => {
+ it('flags ask_user_question (agentsOnly in the real manifest) in both wire shapes', () => {
+ // Guard the data too: the whole assistants-rejection path keys on this flag.
+ expect(manifestToolMap['ask_user_question']?.agentsOnly).toBe(true);
+
+ expect(isAgentsOnlyTool('ask_user_question')).toBe(true);
+ expect(isAgentsOnlyTool({ type: 'function', function: { name: 'ask_user_question' } })).toBe(
+ true,
+ );
+ });
+
+ it('does not flag ordinary manifest tools, unknown tools, or malformed inputs', () => {
+ expect(isAgentsOnlyTool('calculator')).toBe(false);
+ expect(isAgentsOnlyTool('nonexistent_tool')).toBe(false);
+ expect(isAgentsOnlyTool({ type: 'function', function: { name: 'calculator' } })).toBe(false);
+ expect(isAgentsOnlyTool(undefined)).toBe(false);
+ expect(isAgentsOnlyTool({})).toBe(false);
+ expect(isAgentsOnlyTool({ type: 'code_interpreter' })).toBe(false);
+ });
+});
diff --git a/api/app/clients/tools/util/handleTools.js b/api/app/clients/tools/util/handleTools.js
index e4e4726610..a01d4fcdec 100644
--- a/api/app/clients/tools/util/handleTools.js
+++ b/api/app/clients/tools/util/handleTools.js
@@ -12,6 +12,8 @@ const {
SET_MEMORY_TOOL_NAME,
buildWebSearchContext,
DELETE_MEMORY_TOOL_NAME,
+ createAskUserQuestionTool,
+ ASK_USER_QUESTION_TOOL_NAME,
buildWebSearchDynamicContext,
} = require('@librechat/api');
const {
@@ -360,6 +362,9 @@ const loadTools = async ({
});
};
continue;
+ } else if (tool === ASK_USER_QUESTION_TOOL_NAME) {
+ requestedTools[tool] = () => createAskUserQuestionTool();
+ continue;
} else if (tool === SET_MEMORY_TOOL_NAME || tool === DELETE_MEMORY_TOOL_NAME) {
requestedTools[tool] = () =>
buildInlineMemoryTool({
diff --git a/api/package.json b/api/package.json
index b9de475faa..cc0e316433 100644
--- a/api/package.json
+++ b/api/package.json
@@ -46,7 +46,7 @@
"@azure/storage-blob": "^12.30.0",
"@google/genai": "^2.8.0",
"@keyv/redis": "^4.3.3",
- "@librechat/agents": "^3.2.57",
+ "@librechat/agents": "^3.2.61",
"@librechat/api": "*",
"@librechat/data-schemas": "*",
"@microsoft/microsoft-graph-client": "^3.0.7",
diff --git a/api/server/controllers/PluginController.js b/api/server/controllers/PluginController.js
index 7bb21a7c58..15e952cfb8 100644
--- a/api/server/controllers/PluginController.js
+++ b/api/server/controllers/PluginController.js
@@ -22,6 +22,11 @@ const getAvailablePluginsController = async (req, res) => {
/** includedTools takes precedence — filteredTools ignored when both are set. */
const plugins = [];
for (const plugin of uniquePlugins) {
+ /** Agents-runtime-only tools (e.g. ask_user_question) never work on the
+ * legacy plugins endpoint — no run to pause, no resume surface. */
+ if (plugin.agentsOnly === true) {
+ continue;
+ }
if (includeSet.size > 0) {
if (!includeSet.has(plugin.pluginKey)) {
continue;
@@ -66,8 +71,21 @@ const getAvailableTools = async (req, res) => {
const toolDefKeysList = toolDefinitions ? Object.keys(toolDefinitions) : null;
const toolDefKeys = toolDefKeysList ? new Set(toolDefKeysList) : null;
+ /**
+ * `getAvailableTools` serves BOTH tool dialogs — /api/agents/tools and
+ * /api/assistants/tools. Tools flagged `agentsOnly` in the manifest (e.g.
+ * ask_user_question, which pauses an agents run via a LangGraph interrupt)
+ * cannot work on the assistants runtime: it executes tools directly with no
+ * run to pause and no resume surface, so attaching one there guarantees a
+ * permanent tool error. Scope them out of the assistants listing by route.
+ */
+ const isAssistantsRoute = req.baseUrl?.includes('/assistants') === true;
+
const toolsOutput = [];
for (const plugin of uniquePlugins) {
+ if (plugin.agentsOnly === true && isAssistantsRoute) {
+ continue;
+ }
const isToolDefined = toolDefKeys?.has(plugin.pluginKey) === true;
const isToolkit =
plugin.toolkit === true &&
diff --git a/api/server/controllers/PluginController.spec.js b/api/server/controllers/PluginController.spec.js
index b392ab575d..d5d2369b0b 100644
--- a/api/server/controllers/PluginController.spec.js
+++ b/api/server/controllers/PluginController.spec.js
@@ -90,6 +90,18 @@ describe('PluginController', () => {
expect(responseData[0].authenticated).toBeUndefined();
});
+ it('excludes agentsOnly plugins from the legacy plugins endpoint (no run to pause)', async () => {
+ require('~/app/clients/tools').availableTools.push(
+ { name: 'Ask User', pluginKey: 'ask_user_question', description: 'q', agentsOnly: true },
+ { name: 'Plugin2', pluginKey: 'key2', description: 'Second' },
+ );
+
+ await getAvailablePluginsController(mockReq, mockRes);
+
+ const responseData = mockRes.json.mock.calls[0][0];
+ expect(responseData.map((p) => p.pluginKey)).toEqual(['key2']);
+ });
+
it('should filter plugins based on includedTools', async () => {
const mockPlugins = [
{ name: 'Plugin1', pluginKey: 'key1', description: 'First' },
@@ -153,6 +165,36 @@ describe('PluginController', () => {
});
describe('getAvailableTools', () => {
+ it('scopes agentsOnly plugins out of the ASSISTANTS listing but keeps them for agents', async () => {
+ const cached = {
+ ask_user_question: {
+ type: 'function',
+ function: { name: 'ask_user_question', description: 'q', parameters: {} },
+ },
+ };
+ require('~/app/clients/tools').availableTools.push({
+ name: 'Ask User',
+ pluginKey: 'ask_user_question',
+ description: 'q',
+ agentsOnly: true,
+ });
+
+ // Agents route: listed.
+ getCachedTools.mockResolvedValueOnce(cached);
+ mockReq.baseUrl = '/api/agents/tools';
+ await getAvailableTools(mockReq, mockRes);
+ expect(mockRes.json.mock.calls[0][0].map((t) => t.pluginKey)).toContain('ask_user_question');
+
+ // Assistants route: the runtime executes tools with no run to pause — excluded.
+ mockRes.json.mockClear();
+ getCachedTools.mockResolvedValueOnce(cached);
+ mockReq.baseUrl = '/api/assistants/v2/tools';
+ await getAvailableTools(mockReq, mockRes);
+ expect(mockRes.json.mock.calls[0][0].map((t) => t.pluginKey)).not.toContain(
+ 'ask_user_question',
+ );
+ });
+
it('should use filterUniquePlugins to deduplicate combined tools', async () => {
const mockUserTools = {
'user-tool': {
diff --git a/api/server/controllers/agents/__tests__/askUserQuestion.e2e.spec.js b/api/server/controllers/agents/__tests__/askUserQuestion.e2e.spec.js
new file mode 100644
index 0000000000..1976ae69a6
--- /dev/null
+++ b/api/server/controllers/agents/__tests__/askUserQuestion.e2e.spec.js
@@ -0,0 +1,489 @@
+/**
+ * Full-wiring ask_user_question lifecycle e2e.
+ *
+ * Companion to `hitlCheckpoint.e2e.spec.js`, same REAL components: the
+ * `@librechat/agents` Run (FakeChatModel scripted to call the ask tool), the
+ * LazyMongoSaver over mongodb-memory-server, the GenerationJobManager, and the
+ * `/agents/chat/resume` controller via supertest. The seam under test here is
+ * different, though: the interrupt is raised INSIDE a tool body (the tool's
+ * func calls the SDK's `askUserQuestion()` helper, which wraps LangGraph
+ * `interrupt()`), not by the PreToolUse approval gate — and the run carries a
+ * checkpointer but NO `humanInTheLoop` switch and NO hooks, proving the
+ * question flow works with the approval policy fully disabled.
+ */
+const express = require('express');
+const request = require('supertest');
+const mongoose = require('mongoose');
+const { MongoMemoryServer } = require('mongodb-memory-server');
+const { z } = require('zod');
+const { tool } = require('@langchain/core/tools');
+const { HumanMessage } = require('@langchain/core/messages');
+const { Run, Providers, FakeChatModel, askUserQuestion } = require('@librechat/agents');
+
+const mockLogger = { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() };
+
+jest.mock('@librechat/data-schemas', () => ({
+ ...jest.requireActual('@librechat/data-schemas'),
+ logger: mockLogger,
+}));
+
+jest.mock('@librechat/api', () => ({
+ ...jest.requireActual('@librechat/api'),
+ checkAndIncrementPendingRequest: jest.fn(async () => ({ allowed: true })),
+ decrementPendingRequest: jest.fn(async () => {}),
+}));
+
+jest.mock('~/models', () => ({
+ saveMessage: jest.fn(async (req, message) => message),
+ getConvo: jest.fn(async () => null),
+ getMessages: jest.fn(async () => []),
+}));
+
+jest.mock('~/server/cleanup', () => ({
+ disposeClient: jest.fn(),
+}));
+
+jest.mock('~/server/services/MCPRequestContext', () => ({
+ getMCPRequestContext: jest.fn(() => null),
+ cleanupMCPRequestContextForReq: jest.fn(),
+}));
+
+// Import after mocks — these are the REAL implementations.
+const {
+ GenerationJobManager,
+ createStreamServices,
+ buildPendingAction,
+ getAgentCheckpointer,
+ deleteAgentCheckpoint,
+ __resetCheckpointerForTests,
+} = require('@librechat/api');
+const ResumeAgentController = require('~/server/controllers/agents/resume');
+
+const USER_ID = 'ask-e2e-user';
+const MONGO_CFG = { type: 'mongo', ttl: 3600 };
+const ASK_TOOL = 'ask_user_question';
+
+/**
+ * Body-run counter + captured resolution. The body executes TWICE per answered
+ * question by LangGraph contract (pass 1 runs until `interrupt()` throws; the
+ * resume pass re-runs the body from the top and `askUserQuestion()` returns the
+ * host's answer), so `bodyRuns` proves the re-entry semantics and
+ * `resolvedAnswers` proves the answer round-trip.
+ */
+let bodyRuns = 0;
+let resolvedAnswers = [];
+const askTool = tool(
+ async (input) => {
+ bodyRuns += 1;
+ const { answer } = askUserQuestion(input);
+ resolvedAnswers.push(answer);
+ return answer;
+ },
+ {
+ name: ASK_TOOL,
+ description: 'Ask the user a clarifying question and wait for their answer.',
+ schema: z.object({
+ question: z.string(),
+ description: z.string().optional(),
+ options: z.array(z.object({ label: z.string(), value: z.string() })).optional(),
+ }),
+ },
+);
+
+/**
+ * Build a REAL run shaped like production `createRun` for the ask-only case:
+ * durable checkpointer attached, `eagerEventToolExecution` on with the ask
+ * tool excluded (mirrors the planned run.ts wiring) — and, deliberately, NO
+ * `humanInTheLoop` and NO hooks.
+ */
+async function buildAskRun({ saver, responses, toolCalls, runId }) {
+ const run = await Run.create({
+ runId,
+ graphConfig: {
+ type: 'standard',
+ llmConfig: {
+ provider: Providers.OPENAI,
+ model: 'gpt-4o-mini',
+ streaming: true,
+ streamUsage: false,
+ },
+ instructions: 'You are a helpful assistant.',
+ tools: [askTool],
+ compileOptions: { checkpointer: saver },
+ },
+ returnContent: true,
+ customHandlers: {},
+ tokenCounter: (text) => String(text ?? '').length,
+ indexTokenCountMap: {},
+ eagerEventToolExecution: { enabled: true, excludeToolNames: [ASK_TOOL] },
+ });
+ run.Graph.overrideModel = new FakeChatModel({ responses, toolCalls });
+ return run;
+}
+
+/**
+ * Build a REAL run in the PRODUCTION shape: the agents endpoint loads tools
+ * definitions-only, so the run is EVENT-DRIVEN (`toolDefinitions` non-empty flips
+ * the SDK ToolNode to event dispatch) and the ask tool rides `graphTools` — the
+ * SDK's in-graph direct-tool seam (agents#289, > 3.2.57) — because an event-
+ * dispatched tool body executes in the host handler outside the Pregel task
+ * frame, where `interrupt()` throws instead of pausing. This is the mode
+ * `createRun` produces via `buildAgentInput`; the traditional-mode harness above
+ * covers runs with zero toolDefinitions.
+ */
+async function buildAskRunEventMode({ saver, responses, toolCalls, runId }) {
+ const run = await Run.create({
+ runId,
+ graphConfig: {
+ type: 'standard',
+ agents: [
+ {
+ agentId: 'agent-ask-event',
+ provider: Providers.OPENAI,
+ clientOptions: { model: 'gpt-4o-mini', streaming: true, streamUsage: false },
+ instructions: 'You are a helpful assistant.',
+ maxContextTokens: 8000,
+ toolDefinitions: [{ name: 'dummy_event_tool', description: 'host-executed event tool' }],
+ graphTools: [askTool],
+ },
+ ],
+ compileOptions: { checkpointer: saver },
+ },
+ returnContent: true,
+ customHandlers: {},
+ tokenCounter: (text) => String(text ?? '').length,
+ indexTokenCountMap: {},
+ eagerEventToolExecution: { enabled: true, excludeToolNames: [ASK_TOOL] },
+ });
+ run.Graph.overrideModel = new FakeChatModel({ responses, toolCalls });
+ return run;
+}
+
+const runConfig = (conversationId) => ({
+ runName: 'AgentRun',
+ configurable: { thread_id: conversationId, user_id: USER_ID },
+ streamMode: 'values',
+ version: 'v2',
+});
+
+/** Poll until `predicate` returns true (the resume continuation is fire-and-forget). */
+async function waitFor(predicate, { timeoutMs = 10_000, intervalMs = 50 } = {}) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (await predicate()) {
+ return;
+ }
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
+ }
+ throw new Error('waitFor: condition not met within timeout');
+}
+
+async function checkpointCounts(conversationId) {
+ const db = mongoose.connection.db;
+ return {
+ checkpoints: await db
+ .collection('agent_checkpoints')
+ .countDocuments({ thread_id: conversationId }),
+ writes: await db
+ .collection('agent_checkpoint_writes')
+ .countDocuments({ thread_id: conversationId }),
+ };
+}
+
+let mongoServer;
+let saver;
+
+beforeAll(async () => {
+ mongoServer = await MongoMemoryServer.create();
+ await mongoose.connect(mongoServer.getUri());
+ __resetCheckpointerForTests();
+ saver = await getAgentCheckpointer(MONGO_CFG);
+
+ GenerationJobManager.configure({ ...createStreamServices(), cleanupOnComplete: false });
+ GenerationJobManager.initialize();
+ GenerationJobManager.setApprovalExpiredHandler(async (conversationId) => {
+ await deleteAgentCheckpoint(conversationId, MONGO_CFG);
+ });
+}, 60000);
+
+afterAll(async () => {
+ GenerationJobManager.setApprovalExpiredHandler(null);
+ await GenerationJobManager.destroy();
+ await mongoose.disconnect();
+ await mongoServer.stop();
+});
+
+beforeEach(() => {
+ bodyRuns = 0;
+ resolvedAnswers = [];
+ jest.clearAllMocks();
+});
+
+describe('ask_user_question lifecycle (full wiring, approval policy disabled)', () => {
+ jest.setTimeout(30000);
+
+ test('a tool-body interrupt pauses durably and the REAL /resume controller delivers the answer as the tool result', async () => {
+ const conversationId = `ask-e2e-resume-${Date.now()}`;
+ const responseMessageId = 'resp-ask-1';
+
+ // --- Turn 1: the model calls the ask tool → interrupt() from inside the tool body. ---
+ const run = await buildAskRun({
+ saver,
+ responses: ['Let me check with you.'],
+ toolCalls: [
+ {
+ name: ASK_TOOL,
+ args: {
+ question: 'Which environment should I deploy to?',
+ options: [
+ { label: 'Staging', value: 'staging' },
+ { label: 'Production', value: 'production' },
+ ],
+ },
+ id: 'tc_ask_1',
+ type: 'tool_call',
+ },
+ ],
+ runId: responseMessageId,
+ });
+ await run.processStream(
+ { messages: [new HumanMessage('deploy the app')] },
+ runConfig(conversationId),
+ );
+
+ const interrupt = run.getInterrupt();
+ expect(interrupt?.payload?.type).toBe('ask_user_question');
+ expect(interrupt.payload.question).toEqual({
+ question: 'Which environment should I deploy to?',
+ options: [
+ { label: 'Staging', value: 'staging' },
+ { label: 'Production', value: 'production' },
+ ],
+ });
+ expect(bodyRuns).toBe(1); // body entered once; interrupt() threw before any answer
+ expect(resolvedAnswers).toEqual([]);
+ const paused = await checkpointCounts(conversationId);
+ expect(paused.checkpoints).toBeGreaterThan(0); // the interrupt checkpoint is durable
+
+ // --- Pause bookkeeping (mirrors AgentClient.handleRunInterrupt). ---
+ await GenerationJobManager.createJob(conversationId, USER_ID, conversationId);
+ await GenerationJobManager.updateMetadata(conversationId, {
+ endpoint: 'agents',
+ agent_id: 'agent-ask-e2e',
+ responseMessageId,
+ });
+ const pendingAction = buildPendingAction(interrupt.payload, {
+ streamId: conversationId,
+ conversationId,
+ runId: responseMessageId,
+ responseMessageId,
+ ttlMs: 60_000,
+ });
+ expect(await GenerationJobManager.approvals.pause(conversationId, pendingAction)).toBe(true);
+
+ // --- Turn 2: answer through the REAL controller; the thin client rebuilds a REAL run. ---
+ const thinClient = {
+ contentParts: [],
+ artifactPromises: [],
+ conversationId,
+ responseMessageId,
+ pendingApproval: null,
+ async resumeCompletion({ resumeValue, abortController }) {
+ const resumed = await buildAskRun({
+ saver,
+ responses: ['Deploying to staging.'],
+ runId: responseMessageId,
+ });
+ await resumed.resume(resumeValue, {
+ ...runConfig(conversationId),
+ signal: (abortController ?? new AbortController()).signal,
+ });
+ const reInterrupt = resumed.getInterrupt?.();
+ if (reInterrupt?.payload) {
+ this.pendingApproval = reInterrupt.payload;
+ }
+ this.contentParts.push({ type: 'text', text: 'Deploying to staging.' });
+ return resumed;
+ },
+ };
+ const initializeClient = jest.fn(async () => ({ client: thinClient }));
+ const addTitle = jest.fn();
+
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ req.user = { id: USER_ID };
+ req.config = { endpoints: { agents: { checkpointer: MONGO_CFG } }, interfaceConfig: {} };
+ next();
+ });
+ app.post('/api/agents/chat/resume', (req, res, next) =>
+ ResumeAgentController(req, res, next, initializeClient, addTitle),
+ );
+
+ const response = await request(app).post('/api/agents/chat/resume').send({
+ conversationId,
+ actionId: pendingAction.actionId,
+ agent_id: 'agent-ask-e2e',
+ endpoint: 'agents',
+ answer: 'staging',
+ });
+
+ expect(response.status).toBe(200);
+ expect(response.body.status).toBe('resuming');
+ await waitFor(async () => {
+ const liveJob = await GenerationJobManager.getJob(conversationId);
+ return liveJob?.status !== 'requires_action' && liveJob?.status !== 'running';
+ });
+
+ expect(initializeClient).toHaveBeenCalledTimes(1);
+ // Resume pass re-ran the body from the top; askUserQuestion() returned the answer.
+ expect(bodyRuns).toBe(2);
+ expect(resolvedAnswers).toEqual(['staging']);
+ expect(thinClient.pendingApproval).toBeNull(); // no second question — turn completed
+
+ // Terminal state: the checkpoint was pruned by the REAL finalize path.
+ await waitFor(async () => (await checkpointCounts(conversationId)).checkpoints === 0);
+ expect(await checkpointCounts(conversationId)).toEqual({ checkpoints: 0, writes: 0 });
+ });
+
+ test('EVENT-DRIVEN mode (production shape): the graphTools ask tool pauses and resumes over the REAL /resume controller', async () => {
+ const conversationId = `ask-e2e-event-${Date.now()}`;
+ const responseMessageId = 'resp-ask-event-1';
+
+ const run = await buildAskRunEventMode({
+ saver,
+ responses: ['Let me check with you.'],
+ toolCalls: [
+ {
+ name: ASK_TOOL,
+ args: { question: 'Proceed with the migration?' },
+ id: 'tc_ask_ev1',
+ type: 'tool_call',
+ },
+ ],
+ runId: responseMessageId,
+ });
+ await run.processStream(
+ { messages: [new HumanMessage('run the migration')] },
+ runConfig(conversationId),
+ );
+
+ const interrupt = run.getInterrupt();
+ expect(interrupt?.payload?.type).toBe('ask_user_question');
+ expect(interrupt.payload.question).toEqual({ question: 'Proceed with the migration?' });
+ expect(bodyRuns).toBe(1);
+ expect((await checkpointCounts(conversationId)).checkpoints).toBeGreaterThan(0);
+
+ await GenerationJobManager.createJob(conversationId, USER_ID, conversationId);
+ await GenerationJobManager.updateMetadata(conversationId, {
+ endpoint: 'agents',
+ agent_id: 'agent-ask-e2e',
+ responseMessageId,
+ });
+ const pendingAction = buildPendingAction(interrupt.payload, {
+ streamId: conversationId,
+ conversationId,
+ runId: responseMessageId,
+ responseMessageId,
+ ttlMs: 60_000,
+ });
+ expect(await GenerationJobManager.approvals.pause(conversationId, pendingAction)).toBe(true);
+
+ const thinClient = {
+ contentParts: [],
+ artifactPromises: [],
+ conversationId,
+ responseMessageId,
+ pendingApproval: null,
+ async resumeCompletion({ resumeValue, abortController }) {
+ const resumed = await buildAskRunEventMode({
+ saver,
+ responses: ['Migration underway.'],
+ runId: responseMessageId,
+ });
+ await resumed.resume(resumeValue, {
+ ...runConfig(conversationId),
+ signal: (abortController ?? new AbortController()).signal,
+ });
+ this.contentParts.push({ type: 'text', text: 'Migration underway.' });
+ return resumed;
+ },
+ };
+ const initializeClient = jest.fn(async () => ({ client: thinClient }));
+
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ req.user = { id: USER_ID };
+ req.config = { endpoints: { agents: { checkpointer: MONGO_CFG } }, interfaceConfig: {} };
+ next();
+ });
+ app.post('/api/agents/chat/resume', (req, res, next) =>
+ ResumeAgentController(req, res, next, initializeClient, jest.fn()),
+ );
+
+ const response = await request(app).post('/api/agents/chat/resume').send({
+ conversationId,
+ actionId: pendingAction.actionId,
+ agent_id: 'agent-ask-e2e',
+ endpoint: 'agents',
+ answer: 'yes, proceed',
+ });
+
+ expect(response.status).toBe(200);
+ await waitFor(async () => {
+ const liveJob = await GenerationJobManager.getJob(conversationId);
+ return liveJob?.status !== 'requires_action' && liveJob?.status !== 'running';
+ });
+
+ expect(bodyRuns).toBe(2);
+ expect(resolvedAnswers).toEqual(['yes, proceed']);
+ await waitFor(async () => (await checkpointCounts(conversationId)).checkpoints === 0);
+ });
+
+ test('a second question raised after resume re-pauses with a fresh ask_user_question interrupt', async () => {
+ const conversationId = `ask-e2e-seq-${Date.now()}`;
+
+ const run = await buildAskRun({
+ saver,
+ responses: ['First question coming.'],
+ toolCalls: [
+ {
+ name: ASK_TOOL,
+ args: { question: 'Pick a color?' },
+ id: 'tc_ask_q1',
+ type: 'tool_call',
+ },
+ ],
+ runId: 'resp-ask-seq',
+ });
+ await run.processStream({ messages: [new HumanMessage('start')] }, runConfig(conversationId));
+ expect(run.getInterrupt()?.payload?.type).toBe('ask_user_question');
+ expect(bodyRuns).toBe(1);
+
+ // Resume with the first answer; the NEXT model turn asks a second question.
+ const resumed = await buildAskRun({
+ saver,
+ responses: ['And one more thing.'],
+ toolCalls: [
+ {
+ name: ASK_TOOL,
+ args: { question: 'Pick a size?' },
+ id: 'tc_ask_q2',
+ type: 'tool_call',
+ },
+ ],
+ runId: 'resp-ask-seq',
+ });
+ await resumed.resume({ answer: 'blue' }, runConfig(conversationId));
+
+ expect(resolvedAnswers).toEqual(['blue']);
+ const second = resumed.getInterrupt();
+ expect(second?.payload?.type).toBe('ask_user_question');
+ expect(second.payload.question).toEqual({ question: 'Pick a size?' });
+ // q1 body ran twice (pass + resume); q2 body entered once and interrupted.
+ expect(bodyRuns).toBe(3);
+
+ await deleteAgentCheckpoint(conversationId, MONGO_CFG);
+ });
+});
diff --git a/api/server/controllers/agents/__tests__/resume.spec.js b/api/server/controllers/agents/__tests__/resume.spec.js
index dc07de7c7d..c7fb4dbef3 100644
--- a/api/server/controllers/agents/__tests__/resume.spec.js
+++ b/api/server/controllers/agents/__tests__/resume.spec.js
@@ -511,6 +511,20 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => {
expect(res.body.error).toMatch(/answer is required/i);
});
+ it('400 when an ask_user_question answer exceeds the length cap', async () => {
+ mockGenerationJobManager.getJob.mockResolvedValue(makeAskUserJob());
+ const res = await post({
+ conversationId: CONVO_ID,
+ actionId: ACTION_ID,
+ agent_id: AGENT_ID,
+ endpoint: 'agents',
+ answer: 'x'.repeat(16_001),
+ });
+ expect(res.status).toBe(400);
+ expect(res.body.error).toMatch(/maximum length/i);
+ expect(mockGenerationJobManager.approvals.resolve).not.toHaveBeenCalled();
+ });
+
it('400 on an unsupported pending-action type', async () => {
const job = makeToolApprovalJob();
job.metadata.pendingAction.payload = { type: 'totally_unknown' };
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js
index 9581e27c5c..7cb265464e 100644
--- a/api/server/controllers/agents/client.js
+++ b/api/server/controllers/agents/client.js
@@ -42,6 +42,9 @@ const {
getApprovalTtlMs,
isHITLEnabled,
deleteAgentCheckpoint,
+ agentRequestsAskUserQuestion,
+ attachAskUserQuestionArgs,
+ createContentIndexOffsetHandlers,
getRequestMemories,
createMemoryProcessor,
agentHasInlineMemoryTools,
@@ -1233,6 +1236,17 @@ class AgentClient extends BaseClient {
if (resolvedModelParameters) {
resumeContext.model_parameters = resolvedModelParameters;
}
+ // Persist the question onto the paused ask tool_call's args NOW: an
+ // abandoned/expired/stopped pause never reaches the answer-resume stamp,
+ // and the streamed args were dropped (name-less chunks) — without this the
+ // unfinished turn saves an empty ask part the record card can't render.
+ if (interrupt.payload?.type === 'ask_user_question' && Array.isArray(this.contentParts)) {
+ const stamped = attachAskUserQuestionArgs(this.contentParts, interrupt.payload.question);
+ if (stamped !== this.contentParts) {
+ this.contentParts.length = 0;
+ this.contentParts.push(...stamped);
+ }
+ }
const pendingAction = buildPendingAction(interrupt.payload, {
streamId,
conversationId: this.conversationId,
@@ -1625,7 +1639,14 @@ class AgentClient extends BaseClient {
// a Redis flag) can go stale across replicas/restarts and skip the prune
// exactly when an orphan exists, while these are two indexed, usually-empty
// deleteMany ops — correctness over a micro-optimization.
- if (streamId && isHITLEnabled(agentsEConfig?.toolApproval)) {
+ // The gate mirrors createRun's checkpointer condition: the approval policy
+ // OR an ask_user_question-capable agent (which attaches a checkpointer
+ // WITHOUT the approval policy) — an ask pause abandoned via job replacement
+ // or Stop would otherwise rehydrate here and silently duplicate context.
+ if (
+ streamId &&
+ (isHITLEnabled(agentsEConfig?.toolApproval) || agents.some(agentRequestsAskUserQuestion))
+ ) {
await deleteAgentCheckpoint(this.conversationId, agentsEConfig?.checkpointer);
}
@@ -1893,7 +1914,14 @@ class AgentClient extends BaseClient {
initialSessions,
runId: this.responseMessageId,
signal: abortController.signal,
- customHandlers: this.options.eventHandlers,
+ // The rebuilt graph numbers content indices from 0, but the aggregator was
+ // just seeded with the pre-pause parts at those same indices — shift every
+ // resumed step index past the seed, or the new output merges into (or, on a
+ // type mismatch, is silently dropped against) the pre-pause content.
+ customHandlers: createContentIndexOffsetHandlers(
+ this.options.eventHandlers,
+ Array.isArray(seedContent) ? seedContent : [],
+ ),
requestBody: config.configurable.requestBody,
user: createSafeUser(this.options.req?.user),
tenantId: this.options.req?.user?.tenantId,
diff --git a/api/server/controllers/agents/resume.js b/api/server/controllers/agents/resume.js
index cc7512dc6f..4c01063571 100644
--- a/api/server/controllers/agents/resume.js
+++ b/api/server/controllers/agents/resume.js
@@ -5,6 +5,7 @@ const {
isPendingActionStale,
mapToolApprovalResolutions,
mapAskUserAnswer,
+ attachAskUserQuestionAnswer,
findUndecidedToolCalls,
findDisallowedDecisions,
findIncompleteDecisions,
@@ -23,6 +24,13 @@ const {
} = require('~/server/services/MCPRequestContext');
const { saveMessage, getConvo, getMessages } = require('~/models');
+/**
+ * Upper bound on an `ask_user_question` answer (characters). Generous for any real
+ * reply typed into the question card while still bounding what a crafted POST can
+ * inject into the resumed run's ToolMessage.
+ */
+const MAX_ASK_ANSWER_LENGTH = 16_000;
+
/** De-duplicate a merged attachment list by a stable artifact identity. */
function mergeAttachments(existing, incoming) {
const seen = new Set();
@@ -169,6 +177,11 @@ function resolveResumeValue(pendingAction, body) {
if (typeof body.answer !== 'string' || body.answer.length === 0) {
return { status: 400, error: 'An answer is required' };
}
+ // The answer becomes a ToolMessage the model must ingest — bound it like any
+ // other user-controlled wire field rather than trusting the client.
+ if (body.answer.length > MAX_ASK_ANSWER_LENGTH) {
+ return { status: 400, error: 'Answer exceeds the maximum length' };
+ }
return { resumeValue: mapAskUserAnswer({ answer: body.answer }) };
}
return { status: 400, error: 'Unsupported pending action type' };
@@ -600,7 +613,19 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle)
// in-memory store's setContentParts REPLACES the stored array, so reading the
// resume state afterward would see the new (empty) client array and lose the seed.
const resumeState = await GenerationJobManager.getResumeState(streamId);
- const seedContent = resumeState?.aggregatedContent ?? [];
+ let seedContent = resumeState?.aggregatedContent ?? [];
+ // Stamp the answered question onto the paused ask_user_question tool-call part
+ // (args = the pendingAction's authoritative question, output = the user's answer):
+ // the streamed arg chunks carry no tool name so the aggregator dropped them, and
+ // no completion event ever fires for this tool — without this the saved part is
+ // an empty "cancelled-looking" tool call. See attachAskUserQuestionAnswer.
+ if (pendingAction.payload?.type === 'ask_user_question') {
+ seedContent = attachAskUserQuestionAnswer(
+ seedContent,
+ pendingAction.payload.question,
+ req.body.answer,
+ );
+ }
if (client.contentParts) {
GenerationJobManager.setContentParts(streamId, client.contentParts);
}
diff --git a/api/server/controllers/assistants/v1.js b/api/server/controllers/assistants/v1.js
index 19be145795..2a835c8f93 100644
--- a/api/server/controllers/assistants/v1.js
+++ b/api/server/controllers/assistants/v1.js
@@ -8,7 +8,7 @@ const { getStrategyFunctions } = require('~/server/services/Files/strategies');
const { deleteAssistantActions } = require('~/server/services/ActionService');
const { getOpenAIClient, fetchAssistants } = require('./helpers');
const { getCachedTools } = require('~/server/services/Config');
-const { manifestToolMap } = require('~/app/clients/tools');
+const { manifestToolMap, isAgentsOnlyTool } = require('~/app/clients/tools');
/**
* Create an assistant.
@@ -34,6 +34,15 @@ const createAssistant = async (req, res) => {
assistantData.tools = tools
.map((tool) => {
+ /** Agents-runtime-only tools (e.g. ask_user_question) cannot execute on
+ * the assistants runtime — drop them even when posted directly, since
+ * the tools-dialog scoping doesn't gate REST clients or stale payloads. */
+ if (isAgentsOnlyTool(tool)) {
+ logger.warn(
+ `[/assistants] Dropping agents-only tool from assistant payload: ${typeof tool === 'string' ? tool : tool?.function?.name}`,
+ );
+ return undefined;
+ }
if (typeof tool !== 'string') {
return tool;
}
@@ -139,6 +148,15 @@ const patchAssistant = async (req, res) => {
updateData.tools = (updateData.tools ?? [])
.map((tool) => {
+ /** Agents-runtime-only tools (e.g. ask_user_question) cannot execute on
+ * the assistants runtime — drop them even when posted directly, since
+ * the tools-dialog scoping doesn't gate REST clients or stale payloads. */
+ if (isAgentsOnlyTool(tool)) {
+ logger.warn(
+ `[/assistants] Dropping agents-only tool from assistant payload: ${typeof tool === 'string' ? tool : tool?.function?.name}`,
+ );
+ return undefined;
+ }
if (typeof tool !== 'string') {
return tool;
}
diff --git a/api/server/controllers/assistants/v2.js b/api/server/controllers/assistants/v2.js
index cc0e03916d..fa05e1286a 100644
--- a/api/server/controllers/assistants/v2.js
+++ b/api/server/controllers/assistants/v2.js
@@ -3,7 +3,7 @@ const { ToolCallTypes } = require('librechat-data-provider');
const validateAuthor = require('~/server/middleware/assistants/validateAuthor');
const { validateAndUpdateTool } = require('~/server/services/ActionService');
const { getCachedTools } = require('~/server/services/Config');
-const { manifestToolMap } = require('~/app/clients/tools');
+const { manifestToolMap, isAgentsOnlyTool } = require('~/app/clients/tools');
const { updateAssistantDoc } = require('~/models');
const { getOpenAIClient } = require('./helpers');
@@ -32,6 +32,15 @@ const createAssistant = async (req, res) => {
assistantData.tools = tools
.map((tool) => {
+ /** Agents-runtime-only tools (e.g. ask_user_question) cannot execute on
+ * the assistants runtime — drop them even when posted directly, since
+ * the tools-dialog scoping doesn't gate REST clients or stale payloads. */
+ if (isAgentsOnlyTool(tool)) {
+ logger.warn(
+ `[/assistants] Dropping agents-only tool from assistant payload: ${typeof tool === 'string' ? tool : tool?.function?.name}`,
+ );
+ return undefined;
+ }
if (typeof tool !== 'string') {
return tool;
}
@@ -125,6 +134,15 @@ const updateAssistant = async ({ req, openai, assistant_id, updateData }) => {
let hasFileSearch = false;
for (const tool of updateData.tools ?? []) {
+ /** Agents-runtime-only tools (e.g. ask_user_question) cannot execute on
+ * the assistants runtime — drop them even when posted directly, since
+ * the tools-dialog scoping doesn't gate REST clients or stale payloads. */
+ if (isAgentsOnlyTool(tool)) {
+ logger.warn(
+ `[/assistants] Dropping agents-only tool from assistant payload: ${typeof tool === 'string' ? tool : tool?.function?.name}`,
+ );
+ continue;
+ }
const toolDefinitions = (await getCachedTools()) ?? {};
let actualTool = typeof tool === 'string' ? toolDefinitions[tool] : tool;
diff --git a/api/server/routes/agents/__tests__/abort.spec.js b/api/server/routes/agents/__tests__/abort.spec.js
index 15efb19a39..c9cc6b5b0f 100644
--- a/api/server/routes/agents/__tests__/abort.spec.js
+++ b/api/server/routes/agents/__tests__/abort.spec.js
@@ -121,7 +121,10 @@ describe('Agent Abort Endpoint', () => {
expect(response.status).toBe(200);
expect(response.body).toEqual({ success: true, aborted: jobStreamId });
- expect(mockGenerationJobManager.abortJob).toHaveBeenCalledWith(jobStreamId);
+ expect(mockGenerationJobManager.abortJob).toHaveBeenCalledWith(
+ jobStreamId,
+ expect.objectContaining({ transformAbortContent: expect.any(Function) }),
+ );
});
it('should allow abort when job has no userId metadata (backwards compatibility)', async () => {
@@ -327,6 +330,56 @@ describe('Agent Abort Endpoint', () => {
);
});
+ it('stamps a paused ask_user_question via transformAbortContent, before the final SSE emits', async () => {
+ const jobStreamId = 'test-stream-123';
+ const question = { question: 'Deploy where?', options: [{ label: 'Prod', value: 'prod' }] };
+
+ mockGenerationJobManager.getJob.mockResolvedValue({
+ metadata: {
+ userId: 'test-user-123',
+ pendingAction: { payload: { type: 'ask_user_question', question } },
+ },
+ });
+
+ // abortJob applies the transform; capture it and echo the transformed
+ // content back as the result, mirroring the real (Redis) reconstruction
+ // where the ask tool_call arrives with empty args.
+ let capturedTransform;
+ mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => {
+ capturedTransform = options?.transformAbortContent;
+ const rawContent = [
+ { type: 'tool_call', tool_call: { id: 'tc1', name: 'ask_user_question', args: '' } },
+ ];
+ const content = capturedTransform ? capturedTransform(rawContent) : rawContent;
+ return {
+ success: true,
+ jobData: {
+ userMessage: { messageId: 'user-msg-123' },
+ responseMessageId: 'response-msg-456',
+ conversationId: jobStreamId,
+ },
+ content,
+ text: '',
+ };
+ });
+
+ mockSaveMessage.mockResolvedValue();
+
+ const response = await request(app)
+ .post('/api/agents/chat/abort')
+ .send({ conversationId: jobStreamId });
+
+ expect(response.status).toBe(200);
+ expect(capturedTransform).toEqual(expect.any(Function));
+ // The saved (and, in prod, emitted) content carries the stamped args.
+ // saveMessage(reqLike, responseMessage, opts) — the message is arg #2.
+ const savedMessage = mockSaveMessage.mock.calls[0][1];
+ const askPart = savedMessage.content.find(
+ (p) => p?.tool_call?.name === 'ask_user_question',
+ );
+ expect(JSON.parse(askPart.tool_call.args)).toMatchObject({ question: 'Deploy where?' });
+ });
+
it('should handle saveMessage errors gracefully', async () => {
const jobStreamId = 'test-stream-123';
@@ -388,7 +441,10 @@ describe('Agent Abort Endpoint', () => {
expect(response.status).toBe(200);
expect(response.body).toEqual({ success: true, aborted: 'running-stream' });
- expect(mockGenerationJobManager.abortJob).toHaveBeenCalledWith('running-stream');
+ expect(mockGenerationJobManager.abortJob).toHaveBeenCalledWith(
+ 'running-stream',
+ expect.objectContaining({ transformAbortContent: expect.any(Function) }),
+ );
});
it('should not abort paused fallback jobs', async () => {
diff --git a/api/server/routes/agents/index.js b/api/server/routes/agents/index.js
index 5776b31e9e..81612197e8 100644
--- a/api/server/routes/agents/index.js
+++ b/api/server/routes/agents/index.js
@@ -8,6 +8,7 @@ const {
toClientPendingAction,
isHITLEnabled,
deleteAgentCheckpoint,
+ attachAskUserQuestionArgs,
} = require('@librechat/api');
const { createSseStreamTelemetry } = require('@librechat/api/telemetry');
const { logger } = require('@librechat/data-schemas');
@@ -288,7 +289,18 @@ router.post('/chat/abort', configMiddleware, async (req, res) => {
}
logger.debug(`[AgentStream] Job found, aborting: ${jobStreamId}`);
- const abortResult = await GenerationJobManager.abortJob(jobStreamId);
+ // Re-attach a paused ask_user_question's args to the abort content BEFORE
+ // abortJob emits the final SSE. Redis reconstructs abort content from the
+ // chunk log, which never saw the pause-time stamp applied to the in-process
+ // contentParts — stamping inside abortJob (not after) means the LIVE client
+ // gets the question too, not just the saved message on reload.
+ const abortedAskPayload = job.metadata?.pendingAction?.payload;
+ const abortResult = await GenerationJobManager.abortJob(jobStreamId, {
+ transformAbortContent: (content) =>
+ abortedAskPayload?.type === 'ask_user_question' && Array.isArray(content)
+ ? attachAskUserQuestionArgs(content, abortedAskPayload.question)
+ : content,
+ });
logger.debug(`[AgentStream] Job aborted successfully: ${jobStreamId}`, {
abortResultSuccess: abortResult.success,
abortResultUserMessageId: abortResult.jobData?.userMessage?.messageId,
@@ -298,9 +310,12 @@ router.post('/chat/abort', configMiddleware, async (req, res) => {
// HITL: prune the durable checkpoint of a run aborted while paused, so a new turn
// in this conversation can't rehydrate the stale interrupt before the Mongo TTL
// reclaims it (thread_id is the stable conversationId). Idempotent / no-op when
- // HITL is off or nothing was written.
+ // HITL is off or nothing was written. The pendingAction check covers ask-only
+ // pauses (ask_user_question attaches a checkpointer WITHOUT the approval policy):
+ // a job aborted while paused still carries its pendingAction in metadata, which is
+ // exactly the case whose checkpoint would otherwise go stale.
const agentsCfg = req.config?.endpoints?.agents;
- if (isHITLEnabled(agentsCfg?.toolApproval)) {
+ if (isHITLEnabled(agentsCfg?.toolApproval) || job.metadata?.pendingAction != null) {
await deleteAgentCheckpoint(jobStreamId, agentsCfg?.checkpointer).catch((err) =>
logger.error(`[AgentStream] Failed to prune checkpoint on abort: ${jobStreamId}`, err),
);
@@ -315,7 +330,11 @@ router.post('/chat/abort', configMiddleware, async (req, res) => {
abortResult.jobData?.responseMessageId &&
hasPersistableAbortContent(abortResult.content)
) {
- const { jobData, content, text } = abortResult;
+ const { jobData, text } = abortResult;
+ // `abortResult.content` is already stamped by `transformAbortContent`
+ // above (same content the final SSE carried), so the saved message and
+ // the live client agree.
+ const { content } = abortResult;
const responseMessage = {
messageId: jobData.responseMessageId,
parentMessageId: jobData.userMessage.messageId,
diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.js
index 8a51d0ac7f..0b24714ec6 100644
--- a/api/server/services/ToolService.js
+++ b/api/server/services/ToolService.js
@@ -28,6 +28,7 @@ const {
buildMCPAuthRunStepDeltaEvent,
buildMCPAuthRunStepCompletedEvent,
isFileAuthoringToolDefinition,
+ ASK_USER_QUESTION_TOOL_NAME,
} = require('@librechat/api');
const {
Time,
@@ -579,6 +580,9 @@ async function loadToolDefinitionsWrapper({ req, res, agent, streamId = null, to
if (tool === Tools.memory) {
return checkCapability(AgentCapabilities.memory);
}
+ if (tool === ASK_USER_QUESTION_TOOL_NAME) {
+ return checkCapability(AgentCapabilities.ask_user_question);
+ }
if (isActionTool(tool)) {
return actionsEnabled;
}
@@ -1133,6 +1137,8 @@ async function loadAgentTools({
return includesWebSearch;
} else if (tool === Tools.memory) {
return checkCapability(AgentCapabilities.memory);
+ } else if (tool === ASK_USER_QUESTION_TOOL_NAME) {
+ return checkCapability(AgentCapabilities.ask_user_question);
} else if (isActionTool(tool)) {
return actionsEnabled;
} else if (tool?.includes(Constants.mcp_delimiter)) {
diff --git a/api/server/services/__tests__/ToolService.spec.js b/api/server/services/__tests__/ToolService.spec.js
index 9f496c5f3a..db8c2c8cb1 100644
--- a/api/server/services/__tests__/ToolService.spec.js
+++ b/api/server/services/__tests__/ToolService.spec.js
@@ -252,6 +252,44 @@ describe('ToolService - Action Capability Gating', () => {
expect(callArgs.tools).toContain(actionToolName);
});
+ it('should exclude ask_user_question when its capability is disabled (even if tools is enabled)', async () => {
+ // ask_user_question is gated by its OWN capability, like execute_code —
+ // NOT the generic `tools` capability. Here `tools` is on but the ask
+ // capability is not, so the tool must be filtered out.
+ const capabilities = [AgentCapabilities.tools];
+ const req = createMockReq(capabilities);
+ mockGetEndpointsConfig.mockResolvedValue(createEndpointsConfig(capabilities));
+
+ await loadAgentTools({
+ req,
+ res: {},
+ agent: { id: 'agent_123', tools: [regularTool, 'ask_user_question'] },
+ definitionsOnly: true,
+ });
+
+ expect(mockLoadToolDefinitions).toHaveBeenCalledTimes(1);
+ const [callArgs] = mockLoadToolDefinitions.mock.calls[0];
+ expect(callArgs.tools).toContain(regularTool);
+ expect(callArgs.tools).not.toContain('ask_user_question');
+ });
+
+ it('should include ask_user_question when its capability is enabled', async () => {
+ const capabilities = [AgentCapabilities.tools, AgentCapabilities.ask_user_question];
+ const req = createMockReq(capabilities);
+ mockGetEndpointsConfig.mockResolvedValue(createEndpointsConfig(capabilities));
+
+ await loadAgentTools({
+ req,
+ res: {},
+ agent: { id: 'agent_123', tools: [regularTool, 'ask_user_question'] },
+ definitionsOnly: true,
+ });
+
+ expect(mockLoadToolDefinitions).toHaveBeenCalledTimes(1);
+ const [callArgs] = mockLoadToolDefinitions.mock.calls[0];
+ expect(callArgs.tools).toContain('ask_user_question');
+ });
+
it('should not filter MCP tools whose name contains _action (cross-delimiter collision)', async () => {
const mcpToolWithAction = `get_action${Constants.mcp_delimiter}myserver`;
const capabilities = [AgentCapabilities.tools];
@@ -1268,6 +1306,7 @@ describe('ToolService - Action Capability Gating', () => {
expect(defaultAgentCapabilities).toContain(AgentCapabilities.artifacts);
expect(defaultAgentCapabilities).toContain(AgentCapabilities.actions);
expect(defaultAgentCapabilities).toContain(AgentCapabilities.context);
+ expect(defaultAgentCapabilities).toContain(AgentCapabilities.ask_user_question);
expect(defaultAgentCapabilities).toContain(AgentCapabilities.tools);
expect(defaultAgentCapabilities).toContain(AgentCapabilities.chain);
expect(defaultAgentCapabilities).toContain(AgentCapabilities.ocr);
diff --git a/api/server/services/start/tools.js b/api/server/services/start/tools.js
index 90247c8975..c6073b3a73 100644
--- a/api/server/services/start/tools.js
+++ b/api/server/services/start/tools.js
@@ -5,7 +5,12 @@ const { logger } = require('@librechat/data-schemas');
const { zodToJsonSchema } = require('zod-to-json-schema');
const { Tool } = require('@librechat/agents/langchain/tools');
const { Tools, ImageVisionTool } = require('librechat-data-provider');
-const { getToolkitKey, oaiToolkit, geminiToolkit } = require('@librechat/api');
+const {
+ getToolkitKey,
+ oaiToolkit,
+ geminiToolkit,
+ createAskUserQuestionTool,
+} = require('@librechat/api');
const { toolkits } = require('~/app/clients/tools/manifest');
/**
@@ -82,6 +87,7 @@ function loadAndFormatTools({ directory, adminFilter = [], adminIncluded = [] })
const basicToolInstances = [
new Calculator(),
+ createAskUserQuestionTool(),
...Object.values(oaiToolkit),
...Object.values(geminiToolkit),
];
diff --git a/client/src/Providers/ChatFormContext.tsx b/client/src/Providers/ChatFormContext.tsx
index 33940077bb..a1500ac911 100644
--- a/client/src/Providers/ChatFormContext.tsx
+++ b/client/src/Providers/ChatFormContext.tsx
@@ -1,6 +1,11 @@
-import { createFormContext } from './CustomFormContext';
import type { ChatFormValues } from '~/common';
+import { createFormContext } from './CustomFormContext';
-const { CustomFormProvider, useCustomFormContext } = createFormContext<ChatFormValues>();
+const { CustomFormProvider, useCustomFormContext, useOptionalCustomFormContext } =
+ createFormContext<ChatFormValues>();
-export { CustomFormProvider as ChatFormProvider, useCustomFormContext as useChatFormContext };
+export {
+ CustomFormProvider as ChatFormProvider,
+ useCustomFormContext as useChatFormContext,
+ useOptionalCustomFormContext as useOptionalChatFormContext,
+};
diff --git a/client/src/Providers/CustomFormContext.tsx b/client/src/Providers/CustomFormContext.tsx
index cb62b0d402..4616df8579 100644
--- a/client/src/Providers/CustomFormContext.tsx
+++ b/client/src/Providers/CustomFormContext.tsx
@@ -31,6 +31,11 @@ function createFormContext<TFieldValues extends FieldValues>() {
return value;
};
+ /** Non-throwing variant for components that may render outside the provider
+ * (e.g. message content in Share/search views). */
+ const useOptionalCustomFormContext = (): FormContextValue<TFieldValues> | undefined =>
+ useContext(context);
+
const CustomFormProvider = ({
register,
control,
@@ -49,7 +54,7 @@ function createFormContext<TFieldValues extends FieldValues>() {
return <context.Provider value={value}>{children}</context.Provider>;
};
- return { CustomFormProvider, useCustomFormContext };
+ return { CustomFormProvider, useCustomFormContext, useOptionalCustomFormContext };
}
export type { FormContextValue };
diff --git a/client/src/components/Chat/Input/AskUserQuestionPopover.tsx b/client/src/components/Chat/Input/AskUserQuestionPopover.tsx
new file mode 100644
index 0000000000..0e01a70ccd
--- /dev/null
+++ b/client/src/components/Chat/Input/AskUserQuestionPopover.tsx
@@ -0,0 +1,181 @@
+import { memo } from 'react';
+import { useWatch } from 'react-hook-form';
+import { Button } from '@librechat/client';
+import { Check, ChevronDown, CornerDownLeft, TriangleAlert, X } from 'lucide-react';
+import useAskAnswerMode from '~/hooks/Input/useAskAnswerMode';
+import { useChatFormContext } from '~/Providers';
+import { useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+
+/**
+ * Composer popover for a live `ask_user_question` pause. Single-select rows
+ * submit on click; a digit `1..N` activates its row like a click whether
+ * focus is in the composer or on the popover (arrows/Enter highlight+confirm
+ * from the empty composer); multi-select rows toggle checks and an explicit
+ * Submit confirms —
+ * folding in any free-form text typed in the composer, exactly like Enter
+ * would. The footer hint is a button that focuses the composer — the
+ * free-form answer box. Collapse (chevron) hides the popover but keeps
+ * answer mode live via the chat card; × dismisses it entirely. Pure
+ * rendering off {@link useAskAnswerMode}; disappears the moment an answer
+ * submits from any surface, and locks while one is in flight.
+ */
+function AskUserQuestionPopoverContent({
+ conversationId,
+ textAreaRef,
+}: {
+ conversationId: string;
+ textAreaRef?: React.RefObject<HTMLTextAreaElement>;
+}) {
+ const localize = useLocalize();
+ const { control } = useChatFormContext();
+ /** Reactive composer text so multi-select Submit can include (and enable
+ * on) the free-form answer the footer hint invites. */
+ const composerText = (useWatch({ control, name: 'text' }) ?? '') as string;
+ const {
+ liveAsk,
+ options,
+ selected,
+ checked,
+ multiSelect,
+ locked,
+ errored,
+ toggleChecked,
+ canSubmit,
+ submit,
+ submitOption,
+ skip,
+ dismiss,
+ collapse,
+ popoverVisible,
+ handlePopoverKeyDown,
+ } = useAskAnswerMode(conversationId);
+
+ if (!popoverVisible || !liveAsk) {
+ return null;
+ }
+
+ const composerHasText = composerText.trim().length > 0;
+
+ return (
+ <div className="absolute bottom-28 z-10 w-full space-y-2">
+ {/* Digit shortcuts (1..N) work when focus is inside the popover too, not
+ only from the composer — keydown bubbles here from the focused row/
+ control. */}
+ <div
+ className="popover border-token-border-light rounded-2xl border bg-white p-2 shadow-lg dark:bg-gray-700"
+ onKeyDown={handlePopoverKeyDown}
+ >
+ <div className="flex items-start justify-between gap-2 p-2">
+ <div>
+ <p className="text-sm font-medium text-text-primary">{liveAsk.question.question}</p>
+ {liveAsk.question.description != null && liveAsk.question.description.length > 0 && (
+ <p className="mt-0.5 text-xs text-text-secondary">{liveAsk.question.description}</p>
+ )}
+ </div>
+ <div className="flex items-center">
+ <button
+ type="button"
+ aria-label={localize('com_ui_collapse')}
+ className="rounded p-1 text-text-secondary hover:bg-surface-hover"
+ onClick={collapse}
+ >
+ <ChevronDown className="h-4 w-4" aria-hidden="true" />
+ </button>
+ <button
+ type="button"
+ aria-label={localize('com_ui_close')}
+ className="rounded p-1 text-text-secondary hover:bg-surface-hover"
+ onClick={dismiss}
+ >
+ <X className="h-4 w-4" aria-hidden="true" />
+ </button>
+ </div>
+ </div>
+ {options.map((option, index) => {
+ const isChecked = multiSelect && checked.includes(index);
+ return (
+ <button
+ key={option.value}
+ type="button"
+ role={multiSelect ? 'checkbox' : undefined}
+ aria-checked={multiSelect ? isChecked : undefined}
+ disabled={locked}
+ className={cn(
+ 'flex w-full items-center gap-3 rounded-lg p-2 text-left text-sm text-text-primary',
+ selected === index ? 'bg-surface-active' : 'hover:bg-surface-hover',
+ locked ? 'cursor-not-allowed opacity-60' : '',
+ )}
+ onClick={() => (multiSelect ? toggleChecked(index) : submitOption(index))}
+ >
+ <span
+ className={cn(
+ 'flex h-5 w-5 items-center justify-center rounded text-xs',
+ isChecked
+ ? 'bg-surface-submit text-white'
+ : 'bg-surface-tertiary text-text-secondary',
+ )}
+ >
+ {isChecked ? <Check className="h-3.5 w-3.5" aria-hidden="true" /> : index + 1}
+ </span>
+ <span className="flex-1">{option.label}</span>
+ </button>
+ );
+ })}
+ {/** A failed submission keeps the question answerable (controls stay
+ * enabled), but the chat card that would show the error is hidden
+ * while the popover is up — so surface it here for retry guidance. */}
+ {errored && (
+ <div className="flex items-center gap-1.5 px-2 pt-1 text-xs text-text-warning">
+ <TriangleAlert className="h-4 w-4 shrink-0" aria-hidden="true" />
+ {localize('com_ui_ask_answer_error')}
+ </div>
+ )}
+ <div className="flex items-center justify-between gap-2 p-2">
+ <button
+ type="button"
+ className="text-xs italic text-text-secondary hover:text-text-primary hover:underline"
+ onClick={() => textAreaRef?.current?.focus()}
+ >
+ {options.length === 0
+ ? localize('com_ui_ask_type_below_only')
+ : localize('com_ui_ask_type_below')}
+ </button>
+ <div className="flex items-center gap-2">
+ <Button size="sm" variant="outline" disabled={locked} onClick={() => skip()}>
+ {localize('com_ui_skip')}
+ </Button>
+ {multiSelect && options.length > 0 && (
+ <Button
+ size="sm"
+ variant="submit"
+ disabled={locked || (!canSubmit && !composerHasText)}
+ onClick={() => submit(composerText)}
+ >
+ {localize('com_ui_submit')}
+ <CornerDownLeft className="ml-1.5 h-4 w-4" aria-hidden="true" />
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+const AskUserQuestionPopover = memo(function AskUserQuestionPopover({
+ conversationId,
+ textAreaRef,
+}: {
+ conversationId?: string | null;
+ textAreaRef?: React.RefObject<HTMLTextAreaElement>;
+}) {
+ if (conversationId == null || conversationId === 'new') {
+ return null;
+ }
+ return (
+ <AskUserQuestionPopoverContent conversationId={conversationId} textAreaRef={textAreaRef} />
+ );
+});
+
+export default AskUserQuestionPopover;
diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx
index c02ee15e1a..894e234592 100644
--- a/client/src/components/Chat/Input/ChatForm.tsx
+++ b/client/src/components/Chat/Input/ChatForm.tsx
@@ -22,6 +22,8 @@ import {
useAssistantsMapContext,
} from '~/Providers';
import PendingManualSkillsChips from './PendingManualSkillsChips';
+import useAskAnswerMode from '~/hooks/Input/useAskAnswerMode';
+import AskUserQuestionPopover from './AskUserQuestionPopover';
import { cn, getModelSpec, removeFocusRings } from '~/utils';
import { useGetStartupConfig } from '~/data-provider';
import { mainTextareaId, BadgeItem } from '~/common';
@@ -163,12 +165,18 @@ const ChatForm = memo(function ChatForm({
setIsTextAreaFocused(false);
}, []);
+ const answerMode = useAskAnswerMode(conversationId);
+
useAutoSave({
files,
setFiles,
textAreaRef,
conversationId,
isSubmitting,
+ // While a question pause is live the composer is the answer box: drafts
+ // swap to the answer's own key, and the conversation draft is restored
+ // when the question resolves.
+ draftId: answerMode.draftId,
});
const { submitMessage, submitPrompt } = useSubmitMessage();
@@ -188,7 +196,10 @@ const ChatForm = memo(function ChatForm({
submitButtonRef,
setIsScrollable,
disabled: disableInputs,
- placeholder,
+ // The composer IS the free-form answer box while a question pause is live.
+ placeholder: answerMode.active
+ ? (answerMode.otherLabel ?? localize('com_ui_something_else'))
+ : placeholder,
});
useQueryParams({ textAreaRef });
@@ -245,7 +256,15 @@ const ChatForm = memo(function ChatForm({
return (
<form
- onSubmit={methods.handleSubmit(submitMessage)}
+ onSubmit={methods.handleSubmit((data) => {
+ // Answer mode: composer text answers the paused run instead of
+ // starting a new turn (submitText resets the composer itself).
+ // Dismissing the popover restores normal sends.
+ if (answerMode.active && answerMode.submitText(data.text)) {
+ return;
+ }
+ return submitMessage(data);
+ })}
className={cn(
'mx-auto flex w-full flex-row gap-3 transition-[max-width] duration-300 sm:px-2',
maximizeChatSpace ? 'max-w-full' : 'md:max-w-3xl xl:max-w-4xl',
@@ -277,6 +296,9 @@ const ChatForm = memo(function ChatForm({
textAreaRef={textAreaRef}
/>
<PromptsCommand index={index} textAreaRef={textAreaRef} submitPrompt={submitPrompt} />
+ {index === 0 && (
+ <AskUserQuestionPopover conversationId={conversationId} textAreaRef={textAreaRef} />
+ )}
<SkillsCommand
index={index}
textAreaRef={textAreaRef}
@@ -331,7 +353,14 @@ const ChatForm = memo(function ChatForm({
}}
disabled={disableInputs || isNotAppendable}
onPaste={handlePaste}
- onKeyDown={handleKeyDown}
+ onKeyDown={(e) => {
+ // Answer mode consumes option-navigation keys from the
+ // empty composer; everything else follows the normal path.
+ if (answerMode.handleComposerKeyDown(e)) {
+ return;
+ }
+ handleKeyDown(e);
+ }}
onKeyUp={handleKeyUp}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd}
@@ -401,14 +430,19 @@ const ChatForm = memo(function ChatForm({
/>
)}
<div className={`${isRTL ? 'ml-2' : 'mr-2'}`}>
- {isSubmitting && showStopButton ? (
+ {isSubmitting && showStopButton && !answerMode.active ? (
<StopButton stop={handleStopGenerating} setShowStopButton={setShowStopButton} />
) : (
endpoint && (
<SendButton
ref={submitButtonRef}
control={methods.control}
- disabled={filesLoading || isSubmitting || disableInputs || isNotAppendable}
+ disabled={
+ filesLoading ||
+ disableInputs ||
+ isNotAppendable ||
+ (isSubmitting && !answerMode.active)
+ }
/>
)
)}
diff --git a/client/src/components/Chat/Messages/Content/ApprovalContext.tsx b/client/src/components/Chat/Messages/Content/ApprovalContext.tsx
index aed523c42d..cfc301f2bb 100644
--- a/client/src/components/Chat/Messages/Content/ApprovalContext.tsx
+++ b/client/src/components/Chat/Messages/Content/ApprovalContext.tsx
@@ -1,4 +1,5 @@
import { createContext, useCallback, useContext, useMemo, useRef, useState } from 'react';
+import { atom, useRecoilState } from 'recoil';
import { Constants } from 'librechat-data-provider';
import type { Agents } from 'librechat-data-provider';
import {
@@ -6,6 +7,7 @@ import {
useSubmitAskAnswerMutation,
type ResumeAgentFields,
} from '~/data-provider';
+import { resolveAskUserQuestionPart } from '~/utils/approval';
import { ChatContext } from '~/Providers/ChatContext';
import { useGetEphemeralAgent } from '~/store/agents';
@@ -13,6 +15,40 @@ import { useGetEphemeralAgent } from '~/store/agents';
* controls and explain a terminal outcome. */
type ActionStatus = 'idle' | 'submitting' | 'submitted' | 'expired' | 'error';
+/**
+ * Ask-answer submit status keyed by `actionId`. This lives in Recoil, NOT the
+ * {@link ApprovalContext} React state, because the PRIMARY answer surface is
+ * the composer in `ChatForm` — which renders OUTSIDE `ApprovalProvider` (that
+ * only wraps message content). A React context read there degrades to the
+ * inert {@link FALLBACK}, so an in-flight lock / expired status tracked in the
+ * context would never engage for the composer. A global atom is visible to
+ * both the composer (`useAskAnswerMode`) and the message-content card
+ * (`AskUserQuestion`), so a fast double-submit is actually blocked and a
+ * terminal (expired/error) state surfaces on either surface.
+ */
+const askSubmitStatusAtom = atom<Record<string, ActionStatus>>({
+ key: 'askAnswerSubmitStatus',
+ default: {},
+});
+
+/** Shared read/write for the ask-answer submit status. */
+export function useAskSubmitStatus(): {
+ getAskStatus: (actionId: string) => ActionStatus;
+ setAskStatus: (actionId: string, status: ActionStatus) => void;
+} {
+ const [statusMap, setStatusMap] = useRecoilState(askSubmitStatusAtom);
+ const getAskStatus = useCallback(
+ (actionId: string): ActionStatus => statusMap[actionId] ?? 'idle',
+ [statusMap],
+ );
+ const setAskStatus = useCallback(
+ (actionId: string, status: ActionStatus) =>
+ setStatusMap((prev) => ({ ...prev, [actionId]: status })),
+ [setStatusMap],
+ );
+ return { getAskStatus, setAskStatus };
+}
+
interface ApprovalContextValue {
/** Record (or clear) a card's decision for its tool_call within an action. */
setDecision: (
@@ -226,11 +262,15 @@ export default function ApprovalProvider({ children }: { children: React.ReactNo
* than crashing.
*/
export function useResumeSubmit() {
- const conversation = useContext(ChatContext)?.conversation;
+ const chatContext = useContext(ChatContext);
+ const conversation = chatContext?.conversation;
const getEphemeralAgent = useGetEphemeralAgent();
const approvalMutation = useSubmitToolApprovalMutation();
const askMutation = useSubmitAskAnswerMutation();
const { getDecisions, isReady, setStatus } = useApprovalContext();
+ /** Ask status lives in Recoil so it works from the composer (outside the
+ * provider); tool-approval status stays on the context. */
+ const { setAskStatus } = useAskSubmitStatus();
const buildResumeFields = useCallback((): ResumeAgentFields | null => {
const conversationId = conversation?.conversationId;
@@ -271,21 +311,52 @@ export function useResumeSubmit() {
);
const submitAskAnswer = useCallback(
- (actionId: string, answer: string) => {
+ (actionId: string, answer: string, opts?: { onSuccess?: () => void }) => {
const fields = buildResumeFields();
if (!fields || answer.length === 0) {
return;
}
- setStatus(actionId, 'submitting');
+ setAskStatus(actionId, 'submitting');
askMutation.mutate(
{ ...fields, actionId, answer },
{
- onSuccess: () => setStatus(actionId, 'submitted'),
- onError: (error) => setStatus(actionId, isExpiredError(error) ? 'expired' : 'error'),
+ onSuccess: () => {
+ setAskStatus(actionId, 'submitted');
+ /**
+ * Drop the synthetic question part now that the run is resuming: the
+ * server streams the resumed segment at ABSOLUTE content indices
+ * continuing after the pre-pause parts — the exact slot this appended
+ * part occupies. Left in place it blocks that index and the resumed
+ * output doesn't render until finalize. The Q&A's durable record is
+ * the ask_user_question tool call itself.
+ */
+ const messages = chatContext?.getMessages?.();
+ if (messages && chatContext?.setMessages) {
+ let changed = false;
+ const next = messages.map((message) => {
+ const resolved = resolveAskUserQuestionPart(message, actionId, answer);
+ if (resolved !== message) {
+ changed = true;
+ }
+ return resolved;
+ });
+ if (changed) {
+ chatContext.setMessages(next);
+ }
+ }
+ /**
+ * Caller cleanup (clearing the composer / selection) runs ONLY on
+ * success: the composer is the user's sole copy of a free-form
+ * answer, so a failed resume (400 on the answer cap, expiry, a
+ * network error) must leave it intact for the user to trim/retry.
+ */
+ opts?.onSuccess?.();
+ },
+ onError: (error) => setAskStatus(actionId, isExpiredError(error) ? 'expired' : 'error'),
},
);
},
- [askMutation, buildResumeFields, setStatus],
+ [askMutation, buildResumeFields, setAskStatus, chatContext],
);
return { submitToolApproval, submitAskAnswer };
diff --git a/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx b/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx
index 55f85b26af..f1d3794d93 100644
--- a/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx
+++ b/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx
@@ -1,15 +1,21 @@
-import { useState } from 'react';
-import { TriangleAlert } from 'lucide-react';
+import { useContext, useMemo, useState } from 'react';
+import { ChevronUp, TriangleAlert } from 'lucide-react';
import { Button, TextareaAutosize } from '@librechat/client';
import type { Agents } from 'librechat-data-provider';
-import { useApprovalContext, useResumeSubmit } from './ApprovalContext';
+import { useAskSubmitStatus, useResumeSubmit } from './ApprovalContext';
+import useAskAnswerMode from '~/hooks/Input/useAskAnswerMode';
+import { ChatContext } from '~/Providers/ChatContext';
+import { splitOtherOption } from '~/utils/approval';
import { useLocalize } from '~/hooks';
/**
* Renders an `ask_user_question` pause: the prompt, optional description, any
- * curated option buttons, and a free-form text answer. Each path submits the
- * answer through {@link useApprovalContext} to resume the paused run; the
- * continuation arrives on the existing SSE.
+ * curated option buttons, and a free-form text answer. Single-select options
+ * submit on click; multi-select options toggle and Submit confirms the set
+ * (plus any typed text). While this card is the LIVE pause's surface it
+ * shares selection state and submit paths with {@link useAskAnswerMode}, so
+ * the composer, the popover, and this card always agree on what will be
+ * sent; outside a live pause (Share/search) it falls back to local state.
*/
export default function AskUserQuestion({
actionId,
@@ -19,35 +25,118 @@ export default function AskUserQuestion({
question: Agents.AskUserQuestionRequest;
}) {
const localize = useLocalize();
- const { getStatus } = useApprovalContext();
+ const { getAskStatus } = useAskSubmitStatus();
const { submitAskAnswer } = useResumeSubmit();
const [answer, setAnswer] = useState('');
+ const [localChecked, setLocalChecked] = useState<number[]>([]);
+ /**
+ * The composer popover is the primary answer surface — while it's VISIBLE
+ * for this pause, rendering the card too duplicates the question. The card
+ * takes over when the popover is collapsed (answer mode stays live; the
+ * chevron re-expands it) or dismissed (and in contexts without a
+ * ChatContext, where the popover can't exist).
+ */
+ const conversationId = useContext(ChatContext)?.conversation?.conversationId;
+ const answerMode = useAskAnswerMode(conversationId);
+ const { popoverVisible, collapsed, expand, liveAsk } = answerMode;
+ const isLivePause = liveAsk?.actionId === actionId;
- const status = getStatus(actionId);
+ /** Same fold as the popover: a model-supplied catch-all "Other" option
+ * becomes the free-form textarea's placeholder, not a submittable row. */
+ const { choices, otherLabel } = useMemo(
+ () => splitOtherOption(question.options),
+ [question.options],
+ );
+
+ const status = getAskStatus(actionId);
+ if (popoverVisible && isLivePause) {
+ return null;
+ }
const locked = status === 'submitting' || status === 'submitted' || status === 'expired';
if (status === 'submitted') {
return null;
}
+ const multiSelect = question.multiSelect === true;
+ /** Live pause: share the hook's checked set so the composer's Enter and
+ * this card submit exactly what the card displays. */
+ const checkedIndices = isLivePause ? answerMode.checked : localChecked;
+ const toggleIndex = (index: number) => {
+ if (isLivePause) {
+ answerMode.toggleChecked(index);
+ return;
+ }
+ setLocalChecked((prev) =>
+ prev.includes(index) ? prev.filter((i) => i !== index) : [...prev, index],
+ );
+ };
+
const trimmed = answer.trim();
+ const canSubmit = multiSelect
+ ? checkedIndices.length > 0 || trimmed.length > 0
+ : trimmed.length > 0;
+
+ const submitSingle = (index: number) => {
+ if (isLivePause) {
+ answerMode.submitOption(index);
+ return;
+ }
+ const value = choices[index]?.value;
+ if (value != null) {
+ submitAskAnswer(actionId, value);
+ }
+ };
+
+ const submitCombined = () => {
+ const values = multiSelect
+ ? checkedIndices
+ .map((index) => choices[index]?.value)
+ .filter((value): value is string => typeof value === 'string')
+ : [];
+ if (trimmed.length > 0) {
+ values.push(trimmed);
+ }
+ if (values.length === 0) {
+ return;
+ }
+ if (isLivePause) {
+ answerMode.submitAnswer(values);
+ return;
+ }
+ submitAskAnswer(actionId, values.join(', '));
+ };
return (
<div className="my-2 flex w-full flex-col gap-2 rounded-lg border border-border-light bg-surface-secondary p-3">
- <p className="text-sm font-medium text-text-primary">{question.question}</p>
+ <div className="flex items-start justify-between gap-2">
+ <p className="text-sm font-medium text-text-primary">{question.question}</p>
+ {collapsed && isLivePause && (
+ <button
+ type="button"
+ aria-label={localize('com_ui_expand')}
+ className="rounded p-1 text-text-secondary hover:bg-surface-hover"
+ onClick={expand}
+ >
+ <ChevronUp className="h-4 w-4" aria-hidden="true" />
+ </button>
+ )}
+ </div>
{question.description != null && question.description.length > 0 && (
<p className="text-sm text-text-secondary">{question.description}</p>
)}
- {question.options != null && question.options.length > 0 && (
+ {choices.length > 0 && (
<div className="flex flex-wrap gap-2">
- {question.options.map((option) => (
+ {choices.map((option, index) => (
<Button
key={option.value}
size="sm"
- variant="outline"
+ variant={multiSelect && checkedIndices.includes(index) ? 'submit' : 'outline'}
+ role={multiSelect ? 'checkbox' : undefined}
+ aria-checked={multiSelect ? checkedIndices.includes(index) : undefined}
disabled={locked}
- onClick={() => submitAskAnswer(actionId, option.value)}
+ onClick={() => (multiSelect ? toggleIndex(index) : submitSingle(index))}
>
{option.label}
</Button>
@@ -61,18 +150,13 @@ export default function AskUserQuestion({
onChange={(e) => setAnswer(e.target.value)}
minRows={2}
maxRows={12}
- placeholder={localize('com_ui_your_answer')}
+ placeholder={otherLabel ?? localize('com_ui_your_answer')}
className="w-full resize-none rounded-md border border-border-light bg-surface-primary p-2 text-sm"
aria-label={localize('com_ui_your_answer')}
/>
<div className="flex items-center gap-3">
- <Button
- size="sm"
- variant="submit"
- disabled={trimmed.length === 0 || locked}
- onClick={() => submitAskAnswer(actionId, trimmed)}
- >
+ <Button size="sm" variant="submit" disabled={!canSubmit || locked} onClick={submitCombined}>
{status === 'submitting' ? localize('com_ui_submitting') : localize('com_ui_submit')}
</Button>
{status === 'expired' && (
diff --git a/client/src/components/Chat/Messages/Content/AskUserQuestionCall.tsx b/client/src/components/Chat/Messages/Content/AskUserQuestionCall.tsx
new file mode 100644
index 0000000000..3c5f409a33
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/AskUserQuestionCall.tsx
@@ -0,0 +1,90 @@
+import { MessageCircleQuestion } from 'lucide-react';
+import { getSubmittedAskAnswer, parseAskUserQuestionArgs } from '~/utils/approval';
+import { useLocalize } from '~/hooks';
+
+/**
+ * Static rendering of a COMPLETED (or abandoned) `ask_user_question` tool call —
+ * the durable record of the Q&A after the pause resolves. The generic tool card
+ * is wrong here: it labels a no-output call "cancelled" and shows raw JSON args.
+ * The interactive card ({@link AskUserQuestion}) renders only while the pause is
+ * live; this component owns the part everywhere else (history, reload, exports).
+ */
+export default function AskUserQuestionCall({
+ args,
+ output,
+ toolCallId,
+ isSubmitting = false,
+}: {
+ args: string | Record<string, unknown> | undefined;
+ output: string;
+ toolCallId?: string;
+ isSubmitting?: boolean;
+}) {
+ const localize = useLocalize();
+ const question = parseAskUserQuestionArgs(args);
+ /**
+ * The part's own output arrives from the server only at finalize, and the
+ * streaming handler's message copy can overwrite the optimistic store stamp
+ * mid-stream — fall back to the locally-recorded submitted answer so the
+ * Q&A record never blinks out while the resumed segment streams.
+ */
+ const effectiveOutput = output.length > 0 ? output : (getSubmittedAskAnswer(toolCallId) ?? '');
+ const answered = effectiveOutput.length > 0;
+
+ /**
+ * While the turn is live and unanswered, the INTERACTIVE card (rendered from
+ * the pendingAction's synthetic part) owns the question UI — rendering the
+ * durable record too would duplicate it with a misleading "no answer" line.
+ * Once the user answers, the submit handler stamps `output` onto this part,
+ * so the record takes over immediately; an abandoned pause only shows its
+ * "no answer" state after the turn is no longer submitting.
+ */
+ if (!answered && isSubmitting) {
+ return null;
+ }
+
+ /**
+ * Prefer the picked option's label over its wire value when they differ.
+ * Multi-select answers are option values joined by ", " — map the segments
+ * back to labels only when EVERY segment matches an option: values may
+ * legally contain ", " themselves, and a partial mapping could mis-split
+ * such a value into fragments that relabel as options the user never
+ * picked. When any segment misses, show the raw answer untouched.
+ */
+ const exactLabel = question?.options?.find((option) => option.value === effectiveOutput)?.label;
+ const mappedMultiLabel = (() => {
+ if (exactLabel != null || question?.multiSelect !== true || question.options == null) {
+ return null;
+ }
+ const labels = effectiveOutput
+ .split(', ')
+ .map((segment) => question.options?.find((option) => option.value === segment)?.label);
+ return labels.every((label) => label != null) ? labels.join(', ') : null;
+ })();
+ const answerLabel = exactLabel ?? mappedMultiLabel ?? effectiveOutput;
+
+ return (
+ <div className="my-2 flex w-full flex-col gap-1.5 rounded-lg border border-border-light bg-surface-secondary p-3">
+ <div className="flex items-center gap-2 text-xs font-medium text-text-secondary">
+ <MessageCircleQuestion className="h-4 w-4" aria-hidden="true" />
+ {answered ? localize('com_ui_asked') : localize('com_ui_asking')}
+ </div>
+ <p className="text-sm font-medium text-text-primary">
+ {question?.question ?? (answered ? localize('com_ui_asked') : localize('com_ui_asking'))}
+ </p>
+ {question?.description != null && question.description.length > 0 && (
+ <p className="text-sm text-text-secondary">{question.description}</p>
+ )}
+ {answered ? (
+ <p className="text-sm text-text-primary">
+ <span className="font-medium text-text-secondary">{localize('com_ui_you_answered')}</span>{' '}
+ {answerLabel}
+ </p>
+ ) : (
+ <p className="text-sm italic text-text-secondary">
+ {localize('com_ui_question_unanswered')}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/Chat/Messages/Content/Part.tsx b/client/src/components/Chat/Messages/Content/Part.tsx
index 6998cdbe5f..9173d8c896 100644
--- a/client/src/components/Chat/Messages/Content/Part.tsx
+++ b/client/src/components/Chat/Messages/Content/Part.tsx
@@ -23,6 +23,7 @@ import {
SubagentCall,
} from './Parts';
import { getAskUserQuestionPart } from '~/utils/approval';
+import AskUserQuestionCall from './AskUserQuestionCall';
import { isBashProgrammaticToolCall } from './routing';
import { ErrorMessage } from './MessageContent';
import AskUserQuestion from './AskUserQuestion';
@@ -196,6 +197,17 @@ const Part = memo(function Part({
hideAttachments={hideAttachments}
/>
);
+ } else if (toolCall.name === 'ask_user_question') {
+ /** Dedicated Q&A record — the generic tool card would label the
+ * interrupt-resolved call "cancelled" and dump raw JSON args. */
+ return (
+ <AskUserQuestionCall
+ args={toolCall.args}
+ output={typeof toolCall.output === 'string' ? toolCall.output : ''}
+ toolCallId={toolCall.id}
+ isSubmitting={isSubmitting}
+ />
+ );
} else if (toolCall.name === 'skill') {
return (
<SkillCall
diff --git a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
index 52b166b110..955f9b2b47 100644
--- a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
@@ -1,6 +1,6 @@
import { useState, useRef, useMemo, useEffect, useCallback } from 'react';
import { useRecoilValue } from 'recoil';
-import { ChevronDown, Users } from 'lucide-react';
+import { ChevronDown, MessageCircleQuestion, Users } from 'lucide-react';
import { Tools, Constants, ContentTypes, ToolCallTypes } from 'librechat-data-provider';
import type {
TAttachment,
@@ -10,12 +10,13 @@ import type {
} from 'librechat-data-provider';
import type { PartWithIndex } from './ParallelContent';
import { useLocalize, useExpandCollapse, scheduleMessageContentLayoutReconcile } from '~/hooks';
+import { isBashProgrammaticToolCall } from './routing';
+import { ASK_USER_QUESTION } from '~/utils/approval';
import { cn, getToolDisplayLabel } from '~/utils';
import { StackedToolIcons } from './ToolOutput';
import { useMCPIconMap } from '~/hooks/MCP';
import { AttachmentGroup } from './Parts';
import store from '~/store';
-import { isBashProgrammaticToolCall } from './routing';
interface ToolMeta {
name: string;
@@ -133,6 +134,20 @@ export default function ToolCallGroup({
* summary needs to match that tense. */
const subagentsDone = allSubagents && (allCompleted || !isSubmitting);
+ /** `ask_user_question` calls form their own category, mirroring subagents:
+ * a homogeneous group reads "Asking/Asked N questions" (never "Used N
+ * tools — ask_user_question") with a question glyph. A group only exists
+ * at count >= 2, so the plural is always grammatical. */
+ const askQuestionCount = useMemo(
+ () => toolNames.filter((n) => n === ASK_USER_QUESTION).length,
+ [toolNames],
+ );
+ const allAskQuestions = askQuestionCount > 0 && askQuestionCount === count;
+ /** Past tense once the turn is settled — matches the Asking/Asked record
+ * card. While a multi-question turn streams, the still-open question's
+ * tool_call part has no output yet, so keep the present tense. */
+ const askQuestionsDone = allAskQuestions && (allCompleted || !isSubmitting);
+
const toolNameSummary = useMemo(() => {
const seen = new Set<string>();
const labels: string[] = [];
@@ -217,13 +232,24 @@ export default function ToolCallGroup({
[isExpanded, notifyLayoutChange],
);
- const getSubagentLabel = () =>
- subagentsDone
- ? localize('com_ui_ran_n_agents', { 0: String(count) })
- : localize('com_ui_running_n_agents', { 0: String(count) });
- const groupLabel = allSubagents
- ? getSubagentLabel()
- : localize('com_ui_used_n_tools', { 0: String(count) });
+ /** Category-aware header verb: subagents and questions read as their own
+ * category (with tense), everything else is the generic "Used N tools". */
+ const resolveGroupLabel = (): string => {
+ if (allSubagents) {
+ return subagentsDone
+ ? localize('com_ui_ran_n_agents', { 0: String(count) })
+ : localize('com_ui_running_n_agents', { 0: String(count) });
+ }
+ if (allAskQuestions) {
+ return askQuestionsDone
+ ? localize('com_ui_asked_n_questions', { 0: String(count) })
+ : localize('com_ui_asking_n_questions', { 0: String(count) });
+ }
+ return localize('com_ui_used_n_tools', { 0: String(count) });
+ };
+ const groupLabel = resolveGroupLabel();
+ /** Single category glyph for homogeneous groups (else StackedToolIcons). */
+ const CategoryIcon = allSubagents ? Users : MessageCircleQuestion;
const hasActiveToolCall = useMemo(
() => isSubmitting && toolMetadata.some((m) => m && !m.hasOutput),
@@ -246,11 +272,12 @@ export default function ToolCallGroup({
aria-expanded={isExpanded}
aria-label={groupLabel}
>
- {allSubagents ? (
- /** Subagent groups don't have per-tool icons — StackedToolIcons
- * falls back to a generic wrench that reads as "tools" rather
- * than "agents". A single Users glyph matches the individual
- * subagent card header and keeps the visual language consistent. */
+ {allSubagents || allAskQuestions ? (
+ /** Homogeneous category groups get a single category glyph instead
+ * of StackedToolIcons' generic wrenches: a Users glyph for
+ * subagents, a question glyph for ask_user_question — matching
+ * their individual card headers and reading as the category
+ * rather than "tools". */
<div
className={cn(
'flex h-5 w-5 shrink-0 items-center justify-center text-text-secondary',
@@ -258,7 +285,7 @@ export default function ToolCallGroup({
)}
aria-hidden="true"
>
- <Users size={14} />
+ <CategoryIcon size={14} />
</div>
) : (
<StackedToolIcons
@@ -269,10 +296,10 @@ export default function ToolCallGroup({
/>
)}
<span className="tool-status-text font-medium">{groupLabel}</span>
- {/** Hide the tool-name summary for pure-subagent groups — every
- * entry deduplicates to the same "subagent" token, which adds
- * noise without info. Mixed groups keep the summary. */}
- {toolNameSummary && !allSubagents && (
+ {/** Hide the tool-name summary for pure-category groups (subagents /
+ * questions) — every entry deduplicates to the same token, which
+ * adds noise without info. Mixed groups keep the summary. */}
+ {toolNameSummary && !allSubagents && !allAskQuestions && (
<span className="text-xs font-normal text-text-secondary">— {toolNameSummary}</span>
)}
<ChevronDown
diff --git a/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsx b/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsx
index 29ca2e1d68..9cf7d95306 100644
--- a/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsx
@@ -6,6 +6,7 @@ import {
ArrowRightLeft,
FileSearch,
FileText,
+ MessageCircleQuestion,
ScrollText,
Zap,
Wrench,
@@ -27,6 +28,7 @@ export type ToolIconType =
| 'skill'
| 'read_file'
| 'bash_tool'
+ | 'ask_user_question'
| 'action'
| 'generic';
@@ -40,6 +42,7 @@ const ICON_MAP: Record<ToolIconType, React.ComponentType<{ className?: string }>
skill: ScrollText,
read_file: FileText,
bash_tool: BashIcon,
+ ask_user_question: MessageCircleQuestion,
action: Zap,
generic: Wrench,
};
@@ -75,6 +78,9 @@ export function getToolIconType(name: string): ToolIconType {
if (name === 'bash_tool' || name === Constants.BASH_PROGRAMMATIC_TOOL_CALLING) {
return 'bash_tool';
}
+ if (name === 'ask_user_question') {
+ return 'ask_user_question';
+ }
if (name.startsWith(Constants.LC_TRANSFER_TO_)) {
return 'agent_handoff';
}
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
index 058e21f6d2..3abff264a0 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
@@ -1,16 +1,22 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { Tools, Constants, ContentTypes } from 'librechat-data-provider';
-import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import ToolCallGroup from '../ToolCallGroup';
+import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';
import { scheduleMessageContentLayoutReconcile } from '~/hooks';
+import ToolCallGroup from '../ToolCallGroup';
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string, values?: Record<string | number, string>) => {
if (key === 'com_ui_used_n_tools') {
return `Used ${values?.[0]} tools`;
}
+ if (key === 'com_ui_asked_n_questions') {
+ return `Asked ${values?.[0]} questions`;
+ }
+ if (key === 'com_ui_asking_n_questions') {
+ return `Asking ${values?.[0]} questions`;
+ }
if (key === 'com_ui_via_server') {
return `via ${values?.[0]}`;
}
@@ -40,6 +46,11 @@ jest.mock('../ToolOutput', () => ({
jest.mock('lucide-react', () => ({
ChevronDown: () => <span>{'chevron'}</span>,
Users: () => <span>{'users'}</span>,
+ MessageCircleQuestion: () => <span data-testid="question-icon">{'question'}</span>,
+}));
+
+jest.mock('~/utils/approval', () => ({
+ ASK_USER_QUESTION: 'ask_user_question',
}));
jest.mock('~/utils', () => ({
@@ -253,4 +264,49 @@ describe('ToolCallGroup image hoisting', () => {
'bash_tool,bash_tool',
);
});
+
+ it('labels a homogeneous ask_user_question group as its own category', () => {
+ renderGroup({
+ ...baseProps,
+ parts: [
+ { part: makePart('q1', 'blue', 'ask_user_question'), idx: 0 },
+ { part: makePart('q2', 'staging', 'ask_user_question'), idx: 1 },
+ ],
+ });
+
+ // Own verb, not "Used N tools"; question glyph instead of stacked wrenches;
+ // raw-name summary suppressed (like subagent groups).
+ expect(screen.getByRole('button', { name: 'Asked 2 questions' })).toBeInTheDocument();
+ expect(screen.queryByText('Used 2 tools')).not.toBeInTheDocument();
+ expect(screen.getByTestId('question-icon')).toBeInTheDocument();
+ expect(screen.queryByTestId('stacked-icons')).not.toBeInTheDocument();
+ expect(screen.queryByText(/— ask_user_question/)).not.toBeInTheDocument();
+ });
+
+ it('uses the present tense while a multi-question turn is still streaming', () => {
+ renderGroup({
+ ...baseProps,
+ isSubmitting: true,
+ parts: [
+ { part: makePart('q1', 'blue', 'ask_user_question'), idx: 0 },
+ // Second question not yet answered (no output) — turn still in flight.
+ { part: makePart('q2', '', 'ask_user_question'), idx: 1 },
+ ],
+ });
+
+ expect(screen.getByRole('button', { name: 'Asking 2 questions' })).toBeInTheDocument();
+ });
+
+ it('keeps the generic "Used N tools" label for a mixed group containing a question', () => {
+ renderGroup({
+ ...baseProps,
+ parts: [
+ { part: makePart('t1', 'result', 'web_search'), idx: 0 },
+ { part: makePart('q1', 'blue', 'ask_user_question'), idx: 1 },
+ ],
+ });
+
+ expect(screen.getByRole('button', { name: 'Used 2 tools' })).toBeInTheDocument();
+ expect(screen.getByTestId('stacked-icons')).toBeInTheDocument();
+ });
});
diff --git a/client/src/components/SidePanel/Agents/Tools/items/__tests__/catalog.spec.ts b/client/src/components/SidePanel/Agents/Tools/items/__tests__/catalog.spec.ts
index 91db59db56..1733561f0c 100644
--- a/client/src/components/SidePanel/Agents/Tools/items/__tests__/catalog.spec.ts
+++ b/client/src/components/SidePanel/Agents/Tools/items/__tests__/catalog.spec.ts
@@ -17,6 +17,11 @@ const toolInputs: BuildCatalogInputs = {
agentsConfig: { capabilities: [AgentCapabilities.tools] },
};
+const askInputs: BuildCatalogInputs = {
+ ...emptyInputs,
+ agentsConfig: { capabilities: [AgentCapabilities.ask_user_question] },
+};
+
describe('buildCatalog', () => {
test('returns empty when nothing is enabled', () => {
expect(buildCatalog(emptyInputs)).toEqual([]);
@@ -57,6 +62,30 @@ describe('buildCatalog', () => {
expect(systemDefined?.kind === 'builtin' && systemDefined.userProvidedAuth).toBe(false);
});
+ test('surfaces ask_user_question as a BUILTIN (not a plugin) when the server lists it', () => {
+ const askPlugin = makePlugin({ pluginKey: 'ask_user_question', name: 'Ask User' });
+ const items = buildCatalog({ ...askInputs, regularTools: [askPlugin] });
+ const builtin = items.find((i) => i.kind === 'builtin' && i.id === 'ask_user_question');
+ expect(builtin).toBeDefined();
+ expect(builtin?.iconKey).toBe('ask_user_question');
+ // never double-listed in the plugin section
+ expect(items.find((i) => i.kind === 'tool' && i.id === 'ask_user_question')).toBeUndefined();
+ });
+
+ test('gates the ask_user_question builtin on its OWN capability, not the generic tools one', () => {
+ const askPlugin = makePlugin({ pluginKey: 'ask_user_question', name: 'Ask User' });
+ // admin filtered (not in regularTools) despite the capability being on
+ expect(
+ buildCatalog(askInputs).find((i) => i.kind === 'builtin' && i.id === 'ask_user_question'),
+ ).toBeUndefined();
+ // ask_user_question capability off — the generic `tools` capability does NOT stand in for it
+ expect(
+ buildCatalog({ ...toolInputs, regularTools: [askPlugin] }).find(
+ (i) => i.kind === 'builtin' && i.id === 'ask_user_question',
+ ),
+ ).toBeUndefined();
+ });
+
test('hides MCP items when the user lacks MCP permission', () => {
const map = new Map();
map.set('srv', { serverName: 'srv', isConfigured: true, tools: [] });
diff --git a/client/src/components/SidePanel/Agents/Tools/items/__tests__/mutations.spec.ts b/client/src/components/SidePanel/Agents/Tools/items/__tests__/mutations.spec.ts
index e485de9d16..b264a4ccb6 100644
--- a/client/src/components/SidePanel/Agents/Tools/items/__tests__/mutations.spec.ts
+++ b/client/src/components/SidePanel/Agents/Tools/items/__tests__/mutations.spec.ts
@@ -152,3 +152,24 @@ describe('skillsEnabledTransition', () => {
expect(skillsEnabledTransition([], undefined)).toBeUndefined();
});
});
+
+describe('computeToggleAction — ask_user_question builtin', () => {
+ const item = {
+ kind: 'builtin',
+ id: 'ask_user_question',
+ iconKey: 'ask_user_question',
+ name: 'com_ui_ask_user',
+ description: 'com_agents_ask_user_info',
+ } as const;
+
+ test('toggles agent.tools, never a capability field', () => {
+ expect(computeToggleAction(item as never, { selected: false })).toEqual({
+ type: 'tool-add',
+ id: 'ask_user_question',
+ });
+ expect(computeToggleAction(item as never, { selected: true })).toEqual({
+ type: 'tool-remove',
+ id: 'ask_user_question',
+ });
+ });
+});
diff --git a/client/src/components/SidePanel/Agents/Tools/items/__tests__/selectors.spec.ts b/client/src/components/SidePanel/Agents/Tools/items/__tests__/selectors.spec.ts
index e315507eef..12b904e9af 100644
--- a/client/src/components/SidePanel/Agents/Tools/items/__tests__/selectors.spec.ts
+++ b/client/src/components/SidePanel/Agents/Tools/items/__tests__/selectors.spec.ts
@@ -224,3 +224,28 @@ describe('matchesMcpServer', () => {
expect(matchesMcpServer('search_mcp_github_extra', 'github_extra')).toBe(true);
});
});
+
+describe('selection — ask_user_question builtin rides agent.tools', () => {
+ const catalogWithAsk: AgentItem[] = [
+ ...sampleCatalog,
+ {
+ kind: 'builtin',
+ id: 'ask_user_question',
+ name: 'com_ui_ask_user',
+ description: 'com_agents_ask_user_info',
+ iconKey: 'ask_user_question',
+ },
+ ];
+
+ test('selected iff agent.tools contains the tool (no capability field involved)', () => {
+ const selected = deriveSelectedItems(
+ { ...emptyFormState, tools: ['ask_user_question'] },
+ catalogWithAsk,
+ [],
+ );
+ expect(selected.map((i) => i.id)).toContain('ask_user_question');
+
+ const none = deriveSelectedItems(emptyFormState, catalogWithAsk, []);
+ expect(none.map((i) => i.id)).not.toContain('ask_user_question');
+ });
+});
diff --git a/client/src/components/SidePanel/Agents/Tools/items/catalog.ts b/client/src/components/SidePanel/Agents/Tools/items/catalog.ts
index e471828146..e321ceecfa 100644
--- a/client/src/components/SidePanel/Agents/Tools/items/catalog.ts
+++ b/client/src/components/SidePanel/Agents/Tools/items/catalog.ts
@@ -118,6 +118,27 @@ export function buildCatalog(inputs: BuildCatalogInputs): AgentItem[] {
});
}
+ /**
+ * Native tool presented with the builtins (it ships with the app and pauses
+ * the run like a first-class feature), while remaining an `agent.tools`
+ * entry mechanically. Availability is its OWN capability (like execute_code /
+ * web_search), NOT the generic `tools` one — the admin gates questions
+ * independently via `endpoints.agents.capabilities` — AND the server must
+ * still list the plugin (admin didn't filter it out).
+ */
+ if (
+ enabled.has(AgentCapabilities.ask_user_question) &&
+ inputs.regularTools.some((plugin) => plugin.pluginKey === 'ask_user_question')
+ ) {
+ items.push({
+ kind: 'builtin',
+ id: 'ask_user_question',
+ iconKey: 'ask_user_question',
+ name: 'com_ui_ask_user',
+ description: 'com_agents_ask_user_info',
+ });
+ }
+
if (inputs.showMemory) {
items.push({
kind: 'builtin',
@@ -150,6 +171,9 @@ export function buildCatalog(inputs: BuildCatalogInputs): AgentItem[] {
if (enabled.has(AgentCapabilities.tools)) {
for (const plugin of inputs.regularTools) {
+ if (plugin.pluginKey === 'ask_user_question') {
+ continue; // surfaced as a builtin above — don't double-list as a plugin
+ }
items.push({
kind: 'tool',
id: plugin.pluginKey,
diff --git a/client/src/components/SidePanel/Agents/Tools/items/icons.ts b/client/src/components/SidePanel/Agents/Tools/items/icons.ts
index 632346700e..0937552f30 100644
--- a/client/src/components/SidePanel/Agents/Tools/items/icons.ts
+++ b/client/src/components/SidePanel/Agents/Tools/items/icons.ts
@@ -1,5 +1,6 @@
import {
Code,
+ MessageCircleQuestion,
Globe,
Brain,
Sparkles,
@@ -45,6 +46,10 @@ const BUILTIN_ICONS: Record<string, ItemIcon> = {
Icon: Brain,
colorClass: 'bg-indigo-500/15 text-indigo-600 dark:text-indigo-300',
},
+ ask_user_question: {
+ Icon: MessageCircleQuestion,
+ colorClass: 'bg-teal-500/15 text-teal-600 dark:text-teal-300',
+ },
};
const KIND_FALLBACK_ICONS: Record<AgentItem['kind'], ItemIcon> = {
diff --git a/client/src/components/SidePanel/Agents/Tools/items/mutations.ts b/client/src/components/SidePanel/Agents/Tools/items/mutations.ts
index d4fed0a0c1..93272c9a45 100644
--- a/client/src/components/SidePanel/Agents/Tools/items/mutations.ts
+++ b/client/src/components/SidePanel/Agents/Tools/items/mutations.ts
@@ -13,8 +13,13 @@ export type TogglePatch =
| { type: 'action-remove'; actionId: string };
function builtinTogglePatch(id: string, selected: boolean): TogglePatch {
- // Every BuiltinId string equals its AgentCapabilities enum value, so the id
- // is already the form field name.
+ if (id === 'ask_user_question') {
+ // Native tool presented as a builtin — it has no capability field; the
+ // toggle edits agent.tools exactly like a plugin.
+ return selected ? { type: 'tool-remove', id } : { type: 'tool-add', id };
+ }
+ // Every other BuiltinId string equals its AgentCapabilities enum value, so
+ // the id is already the form field name.
const field = id as AgentCapabilities;
if (id === 'artifacts') {
return { type: 'builtin', field, value: selected ? '' : ArtifactModes.DEFAULT };
diff --git a/client/src/components/SidePanel/Agents/Tools/items/selectors.ts b/client/src/components/SidePanel/Agents/Tools/items/selectors.ts
index 93b9670242..b626f4d7e1 100644
--- a/client/src/components/SidePanel/Agents/Tools/items/selectors.ts
+++ b/client/src/components/SidePanel/Agents/Tools/items/selectors.ts
@@ -42,6 +42,9 @@ function isBuiltinSelected(item: AgentItem, form: FormSelection): boolean {
return Boolean(form.artifacts);
case 'context':
return form.context_files.length > 0;
+ case 'ask_user_question':
+ // Native tool presented as a builtin — selection lives in agent.tools.
+ return form.tools.includes('ask_user_question');
default:
return false;
}
diff --git a/client/src/components/SidePanel/Agents/Tools/items/types.ts b/client/src/components/SidePanel/Agents/Tools/items/types.ts
index 26ac623226..d3c563bb0d 100644
--- a/client/src/components/SidePanel/Agents/Tools/items/types.ts
+++ b/client/src/components/SidePanel/Agents/Tools/items/types.ts
@@ -14,7 +14,14 @@ export type BuiltinId =
| `${AgentCapabilities.file_search}`
| `${AgentCapabilities.artifacts}`
| `${AgentCapabilities.memory}`
- | `${AgentCapabilities.context}`;
+ | `${AgentCapabilities.context}`
+ /**
+ * Native tool, not a capability: PRESENTED with the builtins (it ships with
+ * the app and pauses the run, like a first-class feature), but selection and
+ * toggling ride `agent.tools` exactly like a plugin — see the special cases
+ * in `selectors.ts` / `mutations.ts`.
+ */
+ | 'ask_user_question';
export type AgentItemStatus = 'needs_setup';
diff --git a/client/src/hooks/Input/useAskAnswerMode.ts b/client/src/hooks/Input/useAskAnswerMode.ts
new file mode 100644
index 0000000000..aaed8494f1
--- /dev/null
+++ b/client/src/hooks/Input/useAskAnswerMode.ts
@@ -0,0 +1,424 @@
+import { useCallback, useEffect, useMemo } from 'react';
+import { atom, useRecoilState, useRecoilValue } from 'recoil';
+import {
+ useAskSubmitStatus,
+ useResumeSubmit,
+} from '~/components/Chat/Messages/Content/ApprovalContext';
+import {
+ ASK_USER_DECLINED_ANSWER,
+ findLiveAskUserQuestion,
+ splitOtherOption,
+} from '~/utils/approval';
+import { useGetMessagesByConvoId } from '~/data-provider';
+import { useOptionalChatFormContext } from '~/Providers';
+import { getAskAnswerDraftId } from '~/utils';
+import store from '~/store';
+
+/** Dismissed action ids — recoil so every consumer reacts. */
+const dismissedAskActionsAtom = atom<string[]>({
+ key: 'askAnswerModeDismissedActions',
+ default: [],
+});
+
+/** Collapsed action ids: popover chrome hidden, answer mode still live. */
+const collapsedAskActionsAtom = atom<string[]>({
+ key: 'askAnswerModeCollapsedActions',
+ default: [],
+});
+
+/** Currently highlighted option row (keyboard cursor), or nothing. */
+const askAnswerSelectionAtom = atom<number | null>({
+ key: 'askAnswerModeSelection',
+ default: null,
+});
+
+/** Checked option rows for a multi-select question — shared across the
+ * popover, the composer, and the chat card so every surface shows (and
+ * submits) the same set. */
+const askAnswerCheckedAtom = atom<number[]>({
+ key: 'askAnswerModeChecked',
+ default: [],
+});
+
+/**
+ * First-class "answer mode" for a live `ask_user_question` pause. Clicking an
+ * option submits it immediately (multi-select clicks toggle instead, confirmed
+ * by an explicit Submit); arrows/digits from the EMPTY composer steer a
+ * keyboard highlight that Enter fires — but only while the popover is visible,
+ * since it is the only surface that renders the highlight. The composer IS the
+ * free-form answer box — its placeholder swaps, Enter submits the typed text,
+ * and its autosave drafts under `draftId` (the question's own key) so the
+ * conversation draft is stashed on entry and restored once the question
+ * resolves.
+ *
+ * Two ways out short of answering: `collapse` hides the popover chrome but
+ * KEEPS answer mode live (the question renders in the chat card; the composer
+ * still answers), while the × `dismiss` exits answer mode entirely. `Skip`
+ * resumes the run with a canned decline notice.
+ *
+ * `handleComposerKeyDown` only steers selection from the EMPTY composer and
+ * reports whether it consumed the key.
+ */
+export default function useAskAnswerMode(conversationId?: string | null) {
+ const enabled = conversationId != null && conversationId !== 'new';
+ const { data: messages } = useGetMessagesByConvoId(enabled ? conversationId : '', {
+ enabled,
+ });
+ const liveAsk = useMemo(
+ () => (enabled ? findLiveAskUserQuestion(messages) : null),
+ [enabled, messages],
+ );
+ const [dismissedIds, setDismissedIds] = useRecoilState(dismissedAskActionsAtom);
+ const [collapsedIds, setCollapsedIds] = useRecoilState(collapsedAskActionsAtom);
+ const [selected, setSelected] = useRecoilState(askAnswerSelectionAtom);
+ const [checked, setChecked] = useRecoilState(askAnswerCheckedAtom);
+ const saveDrafts = useRecoilValue<boolean>(store.saveDrafts);
+ const { submitAskAnswer } = useResumeSubmit();
+ /** Recoil-backed so the lock/status works from the composer, which renders
+ * outside `ApprovalProvider` (where the context status would be inert). */
+ const { getAskStatus } = useAskSubmitStatus();
+ /** Absent outside ChatView (Share/search render the answer card without the
+ * composer form) — resets are simply skipped there. */
+ const resetComposer = useOptionalChatFormContext()?.reset;
+
+ /** The answer is in flight (or terminal): every submit path must become a
+ * no-op so a double-click or a stray Skip can't race a second resume. */
+ const status = liveAsk != null ? getAskStatus(liveAsk.actionId) : 'idle';
+ const locked = status === 'submitting' || status === 'submitted' || status === 'expired';
+ const dismissed = liveAsk != null && dismissedIds.includes(liveAsk.actionId);
+ /**
+ * An EXPIRED question can no longer be answered, so it drops out of answer
+ * mode entirely: the popover closes, the composer reverts to a normal
+ * composer, and the chat card (always mounted for the live pause) becomes
+ * the sole surface — it carries the only "this action expired" message, so
+ * suppressing it behind an open popover would strand the user at a locked
+ * card with no explanation. (`error`, unlike `expired`, stays active: it is
+ * retryable — see the composer-preserving submit path.)
+ */
+ const active = liveAsk != null && !dismissed && status !== 'expired';
+ const collapsed = active && collapsedIds.includes(liveAsk.actionId);
+ /** The popover renders only while expanded; collapse keeps `active` (and the
+ * composer's answer role) but hands the question display to the chat card. */
+ const popoverVisible = active && !collapsed;
+ const multiSelect = liveAsk != null && liveAsk.question.multiSelect === true;
+ /** Answer-phase draft key: handed to useAutoSave so the composer drafts
+ * under the question's own key while answer mode is live, leaving the
+ * conversation draft untouched until the swap-back restores it. */
+ const draftId = active && liveAsk != null ? getAskAnswerDraftId(liveAsk.actionId) : null;
+ const { choices: options, otherLabel } = useMemo(
+ () => splitOtherOption(liveAsk?.question.options),
+ [liveAsk],
+ );
+
+ /** Selection state is per-question: a new pause must never inherit a stale
+ * highlight (or checks) whose Enter would submit the previous question's
+ * choice. */
+ useEffect(() => {
+ setSelected(null);
+ setChecked([]);
+ }, [liveAsk?.actionId, setSelected, setChecked]);
+
+ const dismiss = useCallback(() => {
+ if (liveAsk) {
+ setDismissedIds((prev) =>
+ prev.includes(liveAsk.actionId) ? prev : [...prev, liveAsk.actionId],
+ );
+ }
+ }, [liveAsk, setDismissedIds]);
+
+ const collapse = useCallback(() => {
+ if (liveAsk) {
+ setCollapsedIds((prev) =>
+ prev.includes(liveAsk.actionId) ? prev : [...prev, liveAsk.actionId],
+ );
+ }
+ }, [liveAsk, setCollapsedIds]);
+
+ const expand = useCallback(() => {
+ if (liveAsk) {
+ setCollapsedIds((prev) => prev.filter((id) => id !== liveAsk.actionId));
+ }
+ }, [liveAsk, setCollapsedIds]);
+
+ const toggleChecked = useCallback(
+ (index: number) => {
+ setSelected(index);
+ setChecked((prev) =>
+ prev.includes(index) ? prev.filter((i) => i !== index) : [...prev, index],
+ );
+ },
+ [setSelected, setChecked],
+ );
+
+ const canSubmit =
+ active &&
+ !locked &&
+ (multiSelect ? checked.length > 0 : typeof selected === 'number' && options[selected] != null);
+
+ /**
+ * Shared answer dispatch: sends the run's resume and clears the phase.
+ * Gated on the live pause (NOT `active` — the chat card must still answer a
+ * dismissed question) and on `locked` (no duplicate resumes while one is in
+ * flight).
+ *
+ * The selection/composer cleanup runs ONLY after the resume is accepted (in
+ * `submitAskAnswer`'s success path): a failed resume — the 16k answer-cap
+ * 400, an expired action, a network error — leaves `status` re-answerable,
+ * so wiping the composer (the user's only copy of a free-form answer) up
+ * front would lose it. The composer only resets when its text was consumed
+ * by the answer or when the draft machinery will restore the stashed
+ * conversation draft; with drafts disabled and an option-click answer the
+ * typed text is left alone.
+ */
+ const submitValues = useCallback(
+ (values: string[], consumedComposerText = false): boolean => {
+ if (!liveAsk || locked || values.length === 0) {
+ return false;
+ }
+ const wasActive = active;
+ submitAskAnswer(liveAsk.actionId, values.join(', '), {
+ onSuccess: () => {
+ setSelected(null);
+ setChecked([]);
+ if (consumedComposerText || (wasActive && saveDrafts)) {
+ resetComposer?.();
+ }
+ },
+ });
+ return true;
+ },
+ [liveAsk, locked, active, saveDrafts, submitAskAnswer, setSelected, setChecked, resetComposer],
+ );
+
+ const checkedValues = useCallback(
+ () =>
+ checked
+ .map((index) => options[index]?.value)
+ .filter((value): value is string => typeof value === 'string'),
+ [checked, options],
+ );
+
+ /** Single-select click path: one click on an option IS the answer. */
+ const submitOption = useCallback(
+ (index: number): boolean => {
+ const option = options[index];
+ if (!option) {
+ return false;
+ }
+ return submitValues([option.value]);
+ },
+ [options, submitValues],
+ );
+
+ /**
+ * Confirm path (Enter / multi-select Submit); true when an answer was sent.
+ * On multi-select any `freeText` (the composer's current value) rides along
+ * with the checked options — the Submit button must never silently drop
+ * text the footer hint invited.
+ */
+ const submit = useCallback(
+ (freeText?: string): boolean => {
+ const trimmed = freeText?.trim() ?? '';
+ if (multiSelect) {
+ const values = checkedValues();
+ if (trimmed.length > 0) {
+ values.push(trimmed);
+ }
+ return submitValues(values, trimmed.length > 0);
+ }
+ if (typeof selected !== 'number') {
+ return false;
+ }
+ return submitOption(selected);
+ },
+ [multiSelect, checkedValues, selected, submitValues, submitOption],
+ );
+
+ /** Composer text answers the question directly; true when consumed. On a
+ * multi-select question any checked options ride along with the text. */
+ const submitText = useCallback(
+ (text: string): boolean => {
+ if (!active || !liveAsk) {
+ return false;
+ }
+ const trimmed = text.trim();
+ if (trimmed.length > 0) {
+ submitValues(multiSelect ? [...checkedValues(), trimmed] : [trimmed], true);
+ }
+ return true;
+ },
+ [active, liveAsk, multiSelect, checkedValues, submitValues],
+ );
+
+ /**
+ * Answer with explicit values from any surface (the chat card's combined
+ * multi-select + free-text submit). Routed through {@link submitValues} so
+ * the in-flight guard and composer/draft cleanup apply everywhere.
+ */
+ const submitAnswer = useCallback(
+ (values: string[]): boolean => submitValues(values),
+ [submitValues],
+ );
+
+ /**
+ * Explicitly decline: resumes the run with a canned notice so the model
+ * knows the user chose not to answer. A client-side dismiss alone would
+ * leave the run paused until expiry — a hung turn.
+ */
+ const skip = useCallback((): boolean => {
+ if (!active) {
+ return false;
+ }
+ return submitValues([ASK_USER_DECLINED_ANSWER]);
+ }, [active, submitValues]);
+
+ /** Selection steering from the empty composer; true when consumed. */
+ const handleComposerKeyDown = useCallback(
+ (e: React.KeyboardEvent<HTMLTextAreaElement>): boolean => {
+ if (!active) {
+ return false;
+ }
+ /**
+ * Let IME composition commit normally: with a CJK keyboard, Enter
+ * commits the in-progress composition rather than submitting, and the
+ * composition buffer can leave `value` empty mid-compose — so bail
+ * before ANY Enter-submit or digit/arrow steering. Mirrors the composer
+ * guard in `useTextarea` (Safari reports `isComposing` inconsistently,
+ * hence the `key`/`keyCode` fallbacks); this handler runs first, so the
+ * guard must live here too.
+ */
+ if (e.nativeEvent.isComposing || e.key === 'Process' || e.keyCode === 229) {
+ return false;
+ }
+ const composerText = e.currentTarget.value;
+ if (composerText.trim().length > 0) {
+ // The composer IS the free-form answer box: Enter submits the typed
+ // text (before useTextarea's submitting-lock can swallow it).
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ return submitText(composerText);
+ }
+ return false;
+ }
+ /**
+ * Option steering (digits/arrows/Enter-on-highlight) only while the
+ * popover — the sole surface that renders the highlight and checks — is
+ * actually visible. While collapsed, digits must type normally: eating
+ * the leading "2" of "2pm works" to move an invisible highlight would
+ * corrupt the free-form answer.
+ */
+ if (options.length === 0 || !popoverVisible) {
+ if (e.key === 'Escape') {
+ dismiss();
+ return true;
+ }
+ return false;
+ }
+ const digit = Number.parseInt(e.key, 10);
+ if (!Number.isNaN(digit) && digit >= 1 && digit <= Math.min(options.length, 9)) {
+ e.preventDefault();
+ if (multiSelect) {
+ toggleChecked(digit - 1);
+ } else {
+ setSelected(digit - 1);
+ }
+ return true;
+ }
+ if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ setSelected(((selected ?? -1) + 1) % options.length);
+ return true;
+ }
+ if (e.key === 'ArrowUp') {
+ e.preventDefault();
+ setSelected(((selected ?? 0) - 1 + options.length) % options.length);
+ return true;
+ }
+ if (e.key === 'Enter' && !e.shiftKey && canSubmit) {
+ e.preventDefault();
+ submit();
+ return true;
+ }
+ if (e.key === 'Escape') {
+ dismiss();
+ return true;
+ }
+ return false;
+ },
+ [
+ active,
+ options,
+ selected,
+ multiSelect,
+ popoverVisible,
+ canSubmit,
+ submit,
+ submitText,
+ toggleChecked,
+ dismiss,
+ setSelected,
+ ],
+ );
+
+ /**
+ * Digit shortcuts while the POPOVER itself holds focus (e.g. a row/Skip
+ * button was clicked or tabbed to). A number activates its option exactly
+ * like a click — single-select submits, multi toggles — so numbers work no
+ * matter where focus landed, not only from the empty composer. No
+ * highlight/Enter dance here: on the popover the options are buttons whose
+ * action IS the click, and intercepting Enter would fight the focused
+ * button. Returns whether the key was consumed.
+ */
+ const handlePopoverKeyDown = useCallback(
+ (e: React.KeyboardEvent): boolean => {
+ if (!active || locked || options.length === 0) {
+ return false;
+ }
+ const digit = Number.parseInt(e.key, 10);
+ if (Number.isNaN(digit) || digit < 1 || digit > Math.min(options.length, 9)) {
+ return false;
+ }
+ e.preventDefault();
+ if (multiSelect) {
+ toggleChecked(digit - 1);
+ } else {
+ submitOption(digit - 1);
+ }
+ return true;
+ },
+ [active, locked, options, multiSelect, toggleChecked, submitOption],
+ );
+
+ return {
+ active,
+ liveAsk,
+ options,
+ dismissed,
+ dismiss,
+ collapsed,
+ collapse,
+ expand,
+ popoverVisible,
+ multiSelect,
+ locked,
+ selected,
+ setSelected,
+ checked,
+ toggleChecked,
+ canSubmit,
+ submit,
+ submitOption,
+ submitText,
+ submitAnswer,
+ skip,
+ handleComposerKeyDown,
+ handlePopoverKeyDown,
+ /** The last submission failed but the question is still answerable — the
+ * popover surfaces this so a composer/popover answer doesn't fail
+ * silently (the chat card's error line is hidden while the popover is up). */
+ errored: status === 'error',
+ /** Model-supplied "Other"-style label, folded into the inline input. */
+ otherLabel,
+ draftId,
+ };
+}
diff --git a/client/src/hooks/Input/useAutoSave.spec.ts b/client/src/hooks/Input/useAutoSave.spec.ts
index 5a5f6b423a..d232490772 100644
--- a/client/src/hooks/Input/useAutoSave.spec.ts
+++ b/client/src/hooks/Input/useAutoSave.spec.ts
@@ -26,9 +26,10 @@ jest.mock('~/utils', () => ({
import React from 'react';
import { renderHook, act } from '@testing-library/react';
import { useRecoilValue } from 'recoil';
+import { Constants, LocalStorageKeys } from 'librechat-data-provider';
import { useChatFormContext } from '~/Providers';
import { useGetFiles } from '~/data-provider';
-import { getDraft, setDraft } from '~/utils';
+import { encodeBase64, getAskAnswerDraftId, getDraft, setDraft } from '~/utils';
import store from '~/store';
import { useAutoSave } from '~/hooks';
@@ -108,3 +109,109 @@ describe('useAutoSave — conversation switching', () => {
expect(mockSetDraft).toHaveBeenCalledWith({ id: 'convo-1', value: 'draft in progress' });
});
});
+
+describe('useAutoSave — ask-answer draft swap', () => {
+ const askDraftId = getAskAnswerDraftId('action-1');
+ const pendingTextKey = `${LocalStorageKeys.TEXT_DRAFT}${Constants.PENDING_CONVO}`;
+
+ afterEach(() => {
+ localStorage.clear();
+ });
+
+ it('stashes the conversation draft and empties the box when answer mode takes the key', () => {
+ const textAreaRef = makeTextAreaRef('half-typed message');
+
+ const { rerender } = renderHook(
+ ({ draftId }: { draftId: string | null }) =>
+ useAutoSave({
+ conversationId: 'convo-1',
+ draftId,
+ textAreaRef,
+ files: new Map(),
+ setFiles: jest.fn(),
+ }),
+ { initialProps: { draftId: null as string | null } },
+ );
+
+ act(() => {
+ rerender({ draftId: askDraftId });
+ });
+
+ expect(mockSetDraft).toHaveBeenCalledWith({ id: 'convo-1', value: 'half-typed message' });
+ expect(mockSetValue).toHaveBeenLastCalledWith('text', '');
+ });
+
+ it('wins over the PENDING_CONVO redirect without migrating the pending draft', () => {
+ // A question pause happens mid-run (isSubmitting), where drafts normally
+ // go to PENDING_CONVO. The ask key must take over AND be exempt from the
+ // PENDING → new-id migration, which would move-and-delete the very draft
+ // the swap-back is supposed to restore.
+ localStorage.setItem(pendingTextKey, encodeBase64('pre-pause draft'));
+ const textAreaRef = makeTextAreaRef('mid-run typing');
+
+ const { rerender } = renderHook(
+ ({ draftId }: { draftId: string | null }) =>
+ useAutoSave({
+ conversationId: 'convo-1',
+ isSubmitting: true,
+ draftId,
+ textAreaRef,
+ files: new Map(),
+ setFiles: jest.fn(),
+ }),
+ { initialProps: { draftId: null as string | null } },
+ );
+
+ act(() => {
+ rerender({ draftId: askDraftId });
+ });
+
+ expect(mockSetDraft).toHaveBeenCalledWith({
+ id: Constants.PENDING_CONVO,
+ value: 'mid-run typing',
+ });
+ expect(localStorage.getItem(pendingTextKey)).toBe(encodeBase64('pre-pause draft'));
+ expect(localStorage.getItem(`${LocalStorageKeys.TEXT_DRAFT}${askDraftId}`)).toBeNull();
+ });
+
+ it('restores the stashed draft when the question resolves', () => {
+ mockGetDraft.mockImplementation((id: string) =>
+ id === Constants.PENDING_CONVO ? 'pre-pause draft' : '',
+ );
+
+ const { rerender } = renderHook(
+ ({ draftId }: { draftId: string | null }) =>
+ useAutoSave({
+ conversationId: 'convo-1',
+ isSubmitting: true,
+ draftId,
+ textAreaRef: makeTextAreaRef(),
+ files: new Map(),
+ setFiles: jest.fn(),
+ }),
+ { initialProps: { draftId: askDraftId as string | null } },
+ );
+
+ act(() => {
+ rerender({ draftId: null });
+ });
+
+ expect(mockSetValue).toHaveBeenLastCalledWith('text', 'pre-pause draft');
+ });
+
+ it('restores a half-typed answer for the same question (reload while paused)', () => {
+ mockGetDraft.mockImplementation((id: string) => (id === askDraftId ? 'half-typed answer' : ''));
+
+ renderHook(() =>
+ useAutoSave({
+ conversationId: 'convo-1',
+ draftId: askDraftId,
+ textAreaRef: makeTextAreaRef(),
+ files: new Map(),
+ setFiles: jest.fn(),
+ }),
+ );
+
+ expect(mockSetValue).toHaveBeenLastCalledWith('text', 'half-typed answer');
+ });
+});
diff --git a/client/src/hooks/Input/useAutoSave.ts b/client/src/hooks/Input/useAutoSave.ts
index b0c588db46..d4dc9eaa97 100644
--- a/client/src/hooks/Input/useAutoSave.ts
+++ b/client/src/hooks/Input/useAutoSave.ts
@@ -1,10 +1,10 @@
+import { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import debounce from 'lodash/debounce';
import { SetterOrUpdater, useRecoilValue } from 'recoil';
-import { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import { LocalStorageKeys, Constants } from 'librechat-data-provider';
import type { TFile } from 'librechat-data-provider';
import type { ExtendedFile } from '~/common';
-import { clearDraft, getDraft, setDraft } from '~/utils';
+import { clearDraft, getDraft, isAskAnswerDraftId, setDraft } from '~/utils';
import { useChatFormContext } from '~/Providers';
import { useGetFiles } from '~/data-provider';
import store from '~/store';
@@ -12,12 +12,20 @@ import store from '~/store';
export const useAutoSave = ({
isSubmitting,
conversationId: _conversationId,
+ draftId,
textAreaRef,
setFiles,
files,
}: {
isSubmitting?: boolean;
conversationId?: string | null;
+ /** Explicit draft-key override — wins over the conversation id AND the
+ * PENDING_CONVO redirect. Set while an `ask_user_question` pause turns the
+ * composer into the answer box: the answer phase drafts under its own key,
+ * and the key change itself drives the save/restore swap below, so the
+ * conversation draft is stashed on entry and restored when the question
+ * resolves. */
+ draftId?: string | null;
textAreaRef?: React.RefObject<HTMLTextAreaElement>;
files: Map<string, ExtendedFile>;
setFiles: SetterOrUpdater<Map<string, ExtendedFile>>;
@@ -25,7 +33,7 @@ export const useAutoSave = ({
// setting for auto-save
const { setValue } = useChatFormContext();
const saveDrafts = useRecoilValue<boolean>(store.saveDrafts);
- const conversationId = isSubmitting ? Constants.PENDING_CONVO : _conversationId;
+ const conversationId = draftId ?? (isSubmitting ? Constants.PENDING_CONVO : _conversationId);
const [currentConversationId, setCurrentConversationId] = useState<string | null>(null);
const fileIds = useMemo(() => Array.from(files.keys()), [files]);
@@ -163,10 +171,14 @@ export const useAutoSave = ({
setFiles(new Map());
try {
- // Check for transition from PENDING_CONVO to a valid conversationId
+ // Check for transition from PENDING_CONVO to a valid conversationId.
+ // An ask-answer key is excluded: it is a temporary overlay, not the
+ // pending draft's destination — migrating would delete the very draft
+ // the answer-phase swap-back is supposed to restore.
if (
prevConversationIdRef.current === Constants.PENDING_CONVO &&
conversationId !== Constants.PENDING_CONVO &&
+ !isAskAnswerDraftId(conversationId) &&
conversationId.length > 3
) {
const pendingDraft = localStorage.getItem(
diff --git a/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts b/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts
index 0e04fb43c6..a3f153d423 100644
--- a/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts
@@ -1848,6 +1848,55 @@ describe('useStepHandler', () => {
});
describe('content type mismatch handling', () => {
+ it('displaces a synthetic ask-user-question card when the resumed segment streams into its slot', () => {
+ const consoleSpy = jest.spyOn(console, 'warn').mockImplementation();
+
+ /** The pause-scoped card is appended at the END of the content — exactly
+ * the ABSOLUTE index the resumed run's first new part arrives at. */
+ const askPart = {
+ type: 'ask_user_question',
+ ask_user_question: { actionId: 'a1', question: { question: 'Which?' } },
+ } as unknown as TMessageContentParts;
+ const responseMessage = createResponseMessage({
+ content: [{ type: ContentTypes.TEXT, text: 'Pre-pause text' }, askPart],
+ });
+ mockGetMessages.mockReturnValue([responseMessage]);
+
+ const { result } = renderHook(() => useStepHandler(createHookParams()));
+
+ act(() => {
+ result.current.syncStepMessage(responseMessage);
+ });
+
+ const runStep = createRunStep({ index: 1 });
+ const submission = createSubmission();
+
+ act(() => {
+ result.current.stepHandler({ event: StepEvents.ON_RUN_STEP, data: runStep }, submission);
+ });
+
+ const textDelta: Agents.MessageDeltaEvent = {
+ id: 'step-1',
+ delta: { content: [{ type: ContentTypes.TEXT, text: 'Resumed answer' }] },
+ };
+
+ act(() => {
+ result.current.stepHandler(
+ { event: StepEvents.ON_MESSAGE_DELTA, data: textDelta },
+ submission,
+ );
+ });
+
+ expect(consoleSpy).not.toHaveBeenCalledWith('Content type mismatch', expect.anything());
+
+ const lastCall = mockSetMessages.mock.calls[mockSetMessages.mock.calls.length - 1];
+ const updated = lastCall[0][lastCall[0].length - 1] as TMessage;
+ const content = updated.content as Array<{ type?: string; text?: string }>;
+ expect(content.some((part) => part?.type === 'ask_user_question')).toBe(false);
+ expect(content[1]).toMatchObject({ type: ContentTypes.TEXT, text: 'Resumed answer' });
+ consoleSpy.mockRestore();
+ });
+
it('should warn on content type mismatch and not overwrite', () => {
const consoleSpy = jest.spyOn(console, 'warn').mockImplementation();
diff --git a/client/src/hooks/SSE/useStepHandler.ts b/client/src/hooks/SSE/useStepHandler.ts
index e9ef6e3227..891dc5bad7 100644
--- a/client/src/hooks/SSE/useStepHandler.ts
+++ b/client/src/hooks/SSE/useStepHandler.ts
@@ -26,6 +26,7 @@ import {
initSubagentAggregatorState,
initSubagentTickerState,
} from '~/utils/subagentContent';
+import { isAskUserQuestionPart } from '~/utils/approval';
import { subagentProgressByToolCallId } from '~/store';
import { MESSAGE_UPDATE_INTERVAL } from '~/common';
@@ -339,6 +340,19 @@ export default function useStepHandler({
updatedContent = updatedContent.filter((part) => !isOAuthToolCallContent(part));
}
+ /**
+ * The synthetic ask-user-question card is pause-scoped UI appended at the end
+ * of the content — exactly the ABSOLUTE index the resumed segment streams
+ * into. Once real content arrives for that slot the pause is over: displace
+ * the card (same displacement pattern as the OAuth prompt above) instead of
+ * dropping the incoming part as a type mismatch. Covers the streaming
+ * handler's own in-flight message copy, reconnecting tabs, and other devices
+ * — the store-level strip on answer submit can't reach those.
+ */
+ if (isAskUserQuestionPart(updatedContent[index])) {
+ updatedContent = updatedContent.filter((part) => !isAskUserQuestionPart(part));
+ }
+
if (!updatedContent[index] && contentType !== ContentTypes.TOOL_CALL) {
updatedContent[index] = { type: contentPart.type as AllContentTypes };
}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 398acf45fa..1f19dd928d 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -9,6 +9,7 @@
"com_a11y_summarize_completed": "Context summarized.",
"com_a11y_summarize_failed": "Summarization failed, continuing with available context.",
"com_a11y_summarize_started": "Summarizing context.",
+ "com_agents_ask_user_info": "Lets the agent pause mid-run to ask you a clarifying question and wait for your answer.",
"com_agents_agent_card_label": "{{name}} agent. {{description}}",
"com_agents_all": "All Agents",
"com_agents_all_category": "All",
@@ -857,6 +858,14 @@
"com_ui_artifacts_options": "Artifacts Options",
"com_ui_artifacts_subtext": "Lets the agent render React, HTML, SVG, Markdown, and Mermaid as interactive artifacts in a side panel instead of plain code blocks.",
"com_ui_ascending": "Asc",
+ "com_ui_ask_answer_error": "Your answer couldn't be sent. Try again.",
+ "com_ui_ask_type_below": "Or type your answer below",
+ "com_ui_ask_type_below_only": "Type your answer below",
+ "com_ui_ask_user": "Ask User",
+ "com_ui_asked": "Asked",
+ "com_ui_asked_n_questions": "Asked {{0}} questions",
+ "com_ui_asking": "Asking",
+ "com_ui_asking_n_questions": "Asking {{0}} questions",
"com_ui_assistant": "Assistant",
"com_ui_assistant_delete_error": "There was an error deleting the assistant",
"com_ui_assistant_deleted": "Successfully deleted assistant",
@@ -1529,6 +1538,7 @@
"com_ui_quality": "Quality",
"com_ui_quote_selections": "{{0}} selections",
"com_ui_quotes_queued": "Quotes added for your next message",
+ "com_ui_question_unanswered": "No answer was given",
"com_ui_ran_n_agents": "Ran {{0}} agents",
"com_ui_read_aloud": "Read aloud",
"com_ui_read_file": "Read {{0}}",
@@ -1723,6 +1733,8 @@
"com_ui_show_qr": "Show QR Code",
"com_ui_sign_in_to_domain": "Sign-in to {{0}}",
"com_ui_size": "Size",
+ "com_ui_skip": "Skip",
+ "com_ui_something_else": "Something else...",
"com_ui_size_sort": "Sort by Size",
"com_ui_skill": "Skill",
"com_ui_skill_content": "Skill Content",
@@ -1866,6 +1878,7 @@
"com_ui_tool_collection_prefix": "A collection of tools from",
"com_ui_tool_credentials_saved": "Credentials saved",
"com_ui_tool_failed": "failed",
+ "com_ui_tool_name_ask_user_question": "Question",
"com_ui_tool_name_code": "Code",
"com_ui_tool_name_code_analysis": "Code Analysis",
"com_ui_tool_name_file_search": "File Search",
@@ -2009,6 +2022,7 @@
"com_ui_x_selected": "{{0}} selected",
"com_ui_xhigh": "Extra High",
"com_ui_yes": "Yes",
+ "com_ui_you_answered": "You answered:",
"com_ui_you": "You",
"com_ui_your_answer": "Type your answer…",
"com_ui_your_api_key": "Your API Key",
diff --git a/client/src/utils/approval.spec.ts b/client/src/utils/approval.spec.ts
index 49265a9995..5b9a3dcc6c 100644
--- a/client/src/utils/approval.spec.ts
+++ b/client/src/utils/approval.spec.ts
@@ -6,6 +6,12 @@ import {
countTaggedApprovalParts,
getAskUserQuestionPart,
findPendingActionMessageIndex,
+ removeAskUserQuestionPart,
+ parseAskUserQuestionArgs,
+ resolveAskUserQuestionPart,
+ getSubmittedAskAnswer,
+ findLiveAskUserQuestion,
+ splitOtherOption,
} from './approval';
const toolCallPart = (id: string, extra: Record<string, unknown> = {}): TMessageContentParts =>
@@ -225,6 +231,168 @@ describe('applyPendingAction — ask_user_question', () => {
});
});
+describe('parseAskUserQuestionArgs', () => {
+ it('parses a JSON-string args payload (the persisted wire shape)', () => {
+ const parsed = parseAskUserQuestionArgs(
+ JSON.stringify({ question: 'Which?', options: [{ label: 'A', value: 'a' }] }),
+ );
+ expect(parsed?.question).toBe('Which?');
+ expect(parsed?.options).toHaveLength(1);
+ });
+
+ it('accepts an already-parsed object', () => {
+ expect(parseAskUserQuestionArgs({ question: 'Which?' })?.question).toBe('Which?');
+ });
+
+ it('degrades to null on empty, malformed, or question-less args', () => {
+ expect(parseAskUserQuestionArgs('')).toBeNull();
+ expect(parseAskUserQuestionArgs('not json')).toBeNull();
+ expect(parseAskUserQuestionArgs('{"no_question": true}')).toBeNull();
+ expect(parseAskUserQuestionArgs(undefined)).toBeNull();
+ });
+
+ it('passes multiSelect through only as a strict boolean true', () => {
+ expect(parseAskUserQuestionArgs({ question: 'Which?', multiSelect: true })?.multiSelect).toBe(
+ true,
+ );
+ expect(
+ parseAskUserQuestionArgs({ question: 'Which?', multiSelect: 'yes' })?.multiSelect,
+ ).toBeUndefined();
+ expect(parseAskUserQuestionArgs({ question: 'Which?' })?.multiSelect).toBeUndefined();
+ });
+});
+
+describe('removeAskUserQuestionPart', () => {
+ it('strips the synthetic part for the matching actionId and keeps everything else', () => {
+ const withCard = applyPendingAction(msg({ content: [textPart('hello')] }), askAction());
+ const stripped = removeAskUserQuestionPart(withCard, 'a1');
+ expect(stripped.content).toHaveLength(1);
+ expect(stripped.content?.[0]).toMatchObject({ type: 'text' });
+ });
+
+ it('returns the same reference when no matching part exists (different actionId / none)', () => {
+ const plain = msg({ content: [textPart('hi')] });
+ expect(removeAskUserQuestionPart(plain, 'a1')).toBe(plain);
+ const withCard = applyPendingAction(plain, askAction());
+ expect(removeAskUserQuestionPart(withCard, 'other-action')).toBe(withCard);
+ });
+
+ it('tolerates non-array content', () => {
+ const weird = msg({ content: undefined as unknown as TMessageContentParts[] });
+ expect(removeAskUserQuestionPart(weird, 'a1')).toBe(weird);
+ });
+});
+
+describe('resolveAskUserQuestionPart', () => {
+ const withCardAndToolCall = () => {
+ const base = msg({
+ content: [
+ textPart('pre-pause'),
+ {
+ type: 'tool_call',
+ tool_call: { id: 'tc1', name: 'ask_user_question', args: '', type: 'tool_call' },
+ } as unknown as TMessageContentParts,
+ ],
+ });
+ return applyPendingAction(base, askAction());
+ };
+
+ it('strips the card and stamps the answer (seeding args from the synthetic question)', () => {
+ const resolved = resolveAskUserQuestionPart(withCardAndToolCall(), 'a1', 'green');
+ const content = resolved.content as Array<{
+ type?: string;
+ tool_call?: Record<string, unknown>;
+ }>;
+ expect(content.some((part) => part?.type === 'ask_user_question')).toBe(false);
+ const toolCall = content[1]?.tool_call as Record<string, unknown>;
+ expect(toolCall.output).toBe('green');
+ expect(toolCall.progress).toBe(1);
+ expect(JSON.parse(toolCall.args as string)).toMatchObject({ question: 'What name?' });
+ });
+
+ it('keeps streamed args when the part already has them', () => {
+ const base = msg({
+ content: [
+ {
+ type: 'tool_call',
+ tool_call: {
+ id: 'tc1',
+ name: 'ask_user_question',
+ args: '{"question":"streamed"}',
+ type: 'tool_call',
+ },
+ } as unknown as TMessageContentParts,
+ ],
+ });
+ const resolved = resolveAskUserQuestionPart(applyPendingAction(base, askAction()), 'a1', 'x');
+ const toolCall = (resolved.content as Array<{ tool_call?: Record<string, unknown> }>)[0]
+ ?.tool_call as Record<string, unknown>;
+ expect(toolCall.args).toBe('{"question":"streamed"}');
+ expect(toolCall.output).toBe('x');
+ });
+
+ it('returns the same reference when the message has no matching synthetic part', () => {
+ const plain = msg({ content: [textPart('hi')] });
+ expect(resolveAskUserQuestionPart(plain, 'a1', 'x')).toBe(plain);
+ });
+
+ it('records the submitted answer by tool_call id (render-layer fallback for mid-stream copies)', () => {
+ resolveAskUserQuestionPart(withCardAndToolCall(), 'a1', 'purple');
+ expect(getSubmittedAskAnswer('tc1')).toBe('purple');
+ expect(getSubmittedAskAnswer('unknown')).toBeUndefined();
+ expect(getSubmittedAskAnswer(undefined)).toBeUndefined();
+ });
+});
+
+describe('splitOtherOption', () => {
+ it("folds a model-supplied 'Other'-style option into the inline placeholder", () => {
+ const { choices, otherLabel } = splitOtherOption([
+ { label: 'Red', value: 'red' },
+ { label: 'Other (type your own)', value: 'other' },
+ ]);
+ expect(choices.map((o) => o.value)).toEqual(['red']);
+ expect(otherLabel).toBe('Other (type your own)');
+ });
+
+ it('matches by label when the value is not literally other', () => {
+ const { choices, otherLabel } = splitOtherOption([
+ { label: 'Blue', value: 'blue' },
+ { label: 'Something else entirely', value: 'custom_answer' },
+ ]);
+ expect(choices).toHaveLength(1);
+ expect(otherLabel).toBe('Something else entirely');
+ });
+
+ it('leaves real choices untouched (no false positives, undefined input)', () => {
+ const options = [
+ { label: 'Red', value: 'red' },
+ { label: 'Mother of pearl', value: 'pearl' },
+ ];
+ expect(splitOtherOption(options)).toEqual({ choices: options });
+ expect(splitOtherOption(undefined)).toEqual({ choices: [] });
+ });
+});
+
+describe('findLiveAskUserQuestion', () => {
+ it('returns the newest live question across messages', () => {
+ const older = applyPendingAction(msg({ content: [] }), askAction());
+ const newer = applyPendingAction(
+ { ...msg({ content: [] }), messageId: 'm2' },
+ askAction({ actionId: 'a2' }),
+ );
+ const found = findLiveAskUserQuestion([older, newer]);
+ expect(found?.actionId).toBe('a2');
+ expect(found?.messageId).toBe('m2');
+ expect(found?.question.question).toBe('What name?');
+ });
+
+ it('returns null with no live question or non-array input', () => {
+ expect(findLiveAskUserQuestion([msg({ content: [textPart('hi')] })])).toBeNull();
+ expect(findLiveAskUserQuestion(null)).toBeNull();
+ expect(findLiveAskUserQuestion(undefined)).toBeNull();
+ });
+});
+
describe('applyPendingAction — unsupported type', () => {
it('returns the original message unchanged', () => {
const message = msg({ content: [textPart('hi')] });
diff --git a/client/src/utils/approval.ts b/client/src/utils/approval.ts
index 6fdf29b8d9..603470a5c0 100644
--- a/client/src/utils/approval.ts
+++ b/client/src/utils/approval.ts
@@ -10,6 +10,13 @@ import type { Agents, TMessage, TMessageContentParts } from 'librechat-data-prov
*/
export const ASK_USER_QUESTION = 'ask_user_question' as const;
+/**
+ * Answer sent when the user explicitly skips a question: the run must resume
+ * (a client-side dismiss would leave it paused until expiry — a hung turn),
+ * and the model needs to know the user declined rather than answered.
+ */
+export const ASK_USER_DECLINED_ANSWER = 'The user chose not to answer this question.';
+
/** Shape of the synthetic content part carrying an ask-user pending action. */
export interface AskUserQuestionPart {
type: typeof ASK_USER_QUESTION;
@@ -25,7 +32,7 @@ export interface AskUserQuestionPart {
* because `AskUserQuestionPart` isn't assignable to the strict
* `TMessageContentParts` union).
*/
-const isAskUserQuestionPart = (part: TMessageContentParts | undefined): boolean =>
+export const isAskUserQuestionPart = (part: Partial<TMessageContentParts> | undefined): boolean =>
(part as { type?: string } | undefined)?.type === ASK_USER_QUESTION &&
part != null &&
ASK_USER_QUESTION in part;
@@ -176,6 +183,228 @@ function applyAskUserQuestion(
return { ...message, content: [...content, askPart] };
}
+/**
+ * Parse an `ask_user_question` tool call's args into the question request shape.
+ * Args arrive as a JSON string on persisted messages (or an object mid-stream);
+ * malformed/empty args degrade to `null` so the caller can render a fallback
+ * label instead of crashing on model output.
+ */
+export function parseAskUserQuestionArgs(
+ args: string | Record<string, unknown> | undefined,
+): Agents.AskUserQuestionRequest | null {
+ let parsed: unknown = args;
+ if (typeof args === 'string') {
+ if (args.trim().length === 0) {
+ return null;
+ }
+ try {
+ parsed = JSON.parse(args);
+ } catch {
+ return null;
+ }
+ }
+ if (
+ parsed == null ||
+ typeof parsed !== 'object' ||
+ typeof (parsed as { question?: unknown }).question !== 'string'
+ ) {
+ return null;
+ }
+ const request = parsed as {
+ question: string;
+ description?: unknown;
+ options?: unknown;
+ multiSelect?: unknown;
+ };
+ /** Model/persisted args are untrusted — normalize instead of crashing the
+ * message render on shapes like `options: {}` or non-string entries. */
+ const options = Array.isArray(request.options)
+ ? request.options.filter(
+ (option): option is Agents.AskUserQuestionOption =>
+ option != null &&
+ typeof (option as { label?: unknown }).label === 'string' &&
+ typeof (option as { value?: unknown }).value === 'string',
+ )
+ : undefined;
+ return {
+ question: request.question,
+ description: typeof request.description === 'string' ? request.description : undefined,
+ options: options && options.length > 0 ? options : undefined,
+ multiSelect: request.multiSelect === true ? true : undefined,
+ };
+}
+
+/**
+ * Removes the synthetic ask-user-question part for `actionId` from a message.
+ * Pure — returns the same message reference when nothing matched.
+ *
+ * Called when the answer submits successfully: the card is pause-scoped UI, and
+ * once the run resumes the server streams new content parts at ABSOLUTE indices
+ * continuing after the pre-pause parts — exactly the slot the appended synthetic
+ * part occupies. Left in place, it blocks the incoming part at that index and
+ * the resumed segment doesn't render until finalize replaces the message.
+ */
+export function removeAskUserQuestionPart(message: TMessage, actionId: string): TMessage {
+ const content = message.content;
+ if (!Array.isArray(content)) {
+ return message;
+ }
+ const nextContent = content.filter(
+ (part) =>
+ !(
+ isAskUserQuestionPart(part) &&
+ (part as unknown as AskUserQuestionPart)[ASK_USER_QUESTION].actionId === actionId
+ ),
+ );
+ if (nextContent.length === content.length) {
+ return message;
+ }
+ return { ...message, content: nextContent };
+}
+
+/**
+ * Session-scoped record of answers the user has submitted, keyed by the ask
+ * tool_call id. Render-layer fallback for `AskUserQuestionCall`: the SSE
+ * step handler evolves its own cached copy of the streaming message, so a
+ * store-level `output` stamp can be overwritten by the next streamed event —
+ * this survives any message-copy churn until finalize delivers the
+ * server-stamped part. Written by {@link resolveAskUserQuestionPart}.
+ */
+const submittedAskAnswers = new Map<string, string>();
+
+/** The locally-submitted answer for an ask tool_call, if any. */
+export function getSubmittedAskAnswer(toolCallId: string | undefined): string | undefined {
+ return toolCallId ? submittedAskAnswers.get(toolCallId) : undefined;
+}
+
+/**
+ * Resolve an answered ask-user-question pause on the client, mirroring the
+ * server's resume-time stamp so the durable Q&A card shows the answer the
+ * moment the user submits (the server-patched part otherwise only arrives at
+ * finalize): removes the synthetic card part for `actionId` AND patches the
+ * newest unanswered `ask_user_question` tool_call with `output = answer`
+ * (seeding `args` from the synthetic part's question when the streamed args
+ * were lost). Pure — returns the input message when nothing matched.
+ */
+export function resolveAskUserQuestionPart(
+ message: TMessage,
+ actionId: string,
+ answer: string,
+): TMessage {
+ const content = message.content;
+ if (!Array.isArray(content)) {
+ return message;
+ }
+ const syntheticPart = content.find(
+ (part) =>
+ isAskUserQuestionPart(part) &&
+ (part as unknown as AskUserQuestionPart)[ASK_USER_QUESTION].actionId === actionId,
+ ) as unknown as AskUserQuestionPart | undefined;
+ if (!syntheticPart) {
+ return message;
+ }
+
+ let patched = false;
+ const nextContent: TMessageContentParts[] = [];
+ for (const part of content) {
+ if (
+ isAskUserQuestionPart(part) &&
+ (part as unknown as AskUserQuestionPart)[ASK_USER_QUESTION].actionId === actionId
+ ) {
+ continue; // strip the pause-scoped card
+ }
+ nextContent.push(part);
+ }
+ for (let i = nextContent.length - 1; i >= 0; i--) {
+ const part = nextContent[i] as { type?: string; tool_call?: Agents.ToolCall } | undefined;
+ const toolCall = part?.tool_call;
+ if (
+ part?.type !== ContentTypes.TOOL_CALL ||
+ toolCall?.name !== ASK_USER_QUESTION ||
+ (typeof toolCall.output === 'string' && toolCall.output.length > 0)
+ ) {
+ continue;
+ }
+ const hasArgs =
+ (typeof toolCall.args === 'string' && toolCall.args.trim().length > 0) ||
+ (toolCall.args != null && typeof toolCall.args === 'object');
+ nextContent[i] = {
+ ...(part as object),
+ tool_call: {
+ ...toolCall,
+ ...(hasArgs ? {} : { args: JSON.stringify(syntheticPart[ASK_USER_QUESTION].question) }),
+ output: answer,
+ progress: 1,
+ },
+ } as TMessageContentParts;
+ if (typeof toolCall.id === 'string' && toolCall.id.length > 0) {
+ submittedAskAnswers.set(toolCall.id, answer);
+ }
+ patched = true;
+ break;
+ }
+
+ if (!patched && nextContent.length === content.length) {
+ return message;
+ }
+ return { ...message, content: nextContent };
+}
+
+/**
+ * Splits a model-supplied catch-all "Other"-style option away from the real
+ * choices. The answer UI always renders its own inline free-form row, so a
+ * model option like "Other (type your own)" would duplicate it — instead its
+ * label becomes the inline input's placeholder. Conservative match: value
+ * `other` (the shape the tool description used to suggest) or a label that
+ * reads as a free-form invitation.
+ */
+export function splitOtherOption(options: Agents.AskUserQuestionOption[] | undefined): {
+ choices: Agents.AskUserQuestionOption[];
+ otherLabel?: string;
+} {
+ const list = options ?? [];
+ const isOther = (option: Agents.AskUserQuestionOption): boolean =>
+ option.value.trim().toLowerCase() === 'other' ||
+ /^other\b|something else|type (my|your) own|free[- ]?form/i.test(option.label);
+ const otherOption = [...list].reverse().find(isOther);
+ if (!otherOption) {
+ return { choices: list };
+ }
+ return {
+ choices: list.filter((option) => option !== otherOption),
+ otherLabel: otherOption.label,
+ };
+}
+
+/**
+ * Finds the live (unanswered) ask-user-question pause across a conversation's
+ * messages — the newest synthetic part wins. Drives the composer popover: the
+ * part exists exactly while a pause is live (applied on `on_pending_action`,
+ * stripped when the answer submits), so its presence IS the popover signal.
+ */
+export function findLiveAskUserQuestion(
+ messages: TMessage[] | null | undefined,
+): { actionId: string; question: Agents.AskUserQuestionRequest; messageId: string } | null {
+ if (!Array.isArray(messages)) {
+ return null;
+ }
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const message = messages[i];
+ const content = message?.content;
+ if (!Array.isArray(content)) {
+ continue;
+ }
+ for (let j = content.length - 1; j >= 0; j--) {
+ const part = content[j];
+ if (isAskUserQuestionPart(part)) {
+ const ask = (part as unknown as AskUserQuestionPart)[ASK_USER_QUESTION];
+ return { actionId: ask.actionId, question: ask.question, messageId: message.messageId };
+ }
+ }
+ }
+ return null;
+}
+
/**
* Applies a {@link Agents.PendingAction} onto the target response message,
* dispatching on the interrupt type. Pure — returns a new message only when the
diff --git a/client/src/utils/drafts.ts b/client/src/utils/drafts.ts
index 2e47c383b1..15298cd3d6 100644
--- a/client/src/utils/drafts.ts
+++ b/client/src/utils/drafts.ts
@@ -44,3 +44,18 @@ export const setDraft = ({ id, value }: { id: string; value?: string }) => {
export const getDraft = (id?: string): string | null =>
decodeBase64((localStorage.getItem(`${LocalStorageKeys.TEXT_DRAFT}${id ?? ''}`) ?? '') || '');
+
+/**
+ * Draft-key prefix for a live `ask_user_question` answer phase. While the
+ * composer doubles as the free-form answer box, its autosave switches to a key
+ * derived from the pause's action id — so the conversation's own draft is left
+ * untouched and comes back once the question resolves, and a half-typed answer
+ * survives reloads/navigation for as long as its question stays live.
+ */
+export const ASK_ANSWER_DRAFT_PREFIX = 'ask-answer:';
+
+export const getAskAnswerDraftId = (actionId: string): string =>
+ `${ASK_ANSWER_DRAFT_PREFIX}${actionId}`;
+
+export const isAskAnswerDraftId = (id?: string | null): boolean =>
+ typeof id === 'string' && id.startsWith(ASK_ANSWER_DRAFT_PREFIX);
diff --git a/client/src/utils/toolLabels.ts b/client/src/utils/toolLabels.ts
index a519e65382..ffb1c74630 100644
--- a/client/src/utils/toolLabels.ts
+++ b/client/src/utils/toolLabels.ts
@@ -21,6 +21,7 @@ export const TOOL_FRIENDLY_NAME_KEYS: Record<string, TranslationKeys> = {
file_search: 'com_ui_tool_name_file_search',
code_interpreter: 'com_ui_tool_name_code_analysis',
retrieval: 'com_ui_tool_name_file_search',
+ ask_user_question: 'com_ui_tool_name_ask_user_question',
};
export interface ParsedToolName {
diff --git a/package-lock.json b/package-lock.json
index 783b1f4ee0..280c7906ae 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -61,7 +61,7 @@
"@azure/storage-blob": "^12.30.0",
"@google/genai": "^2.8.0",
"@keyv/redis": "^4.3.3",
- "@librechat/agents": "^3.2.57",
+ "@librechat/agents": "^3.2.61",
"@librechat/api": "*",
"@librechat/data-schemas": "*",
"@microsoft/microsoft-graph-client": "^3.0.7",
@@ -9880,9 +9880,9 @@
}
},
"node_modules/@librechat/agents": {
- "version": "3.2.57",
- "resolved": "https://registry.npmjs.org/@librechat/agents/-/agents-3.2.57.tgz",
- "integrity": "sha512-utC5z5GpNP4U8HAFPtxmFHt1V72H9cP7rNN3hQx//CH18z//hP623qzgnjo6ZkbLgmu4Gc/GfgykT/svndF+Dg==",
+ "version": "3.2.61",
+ "resolved": "https://registry.npmjs.org/@librechat/agents/-/agents-3.2.61.tgz",
+ "integrity": "sha512-OGdyceeS5IlgWuItxv/+58a/oM0kjZo6NJYIVaIFGBAZregjOJ5i12Yq1ew2EbSws1R8UTAA7/ee0p2p0cduqg==",
"license": "MIT",
"dependencies": {
"@anthropic-ai/sdk": "^0.103.0",
@@ -9903,8 +9903,8 @@
"@langfuse/langchain": "^5.4.1",
"@langfuse/otel": "^5.4.1",
"@langfuse/tracing": "^5.4.1",
- "@opentelemetry/context-async-hooks": "2.7.1",
- "@opentelemetry/sdk-node": "^0.218.0",
+ "@opentelemetry/context-async-hooks": "^2.9.0",
+ "@opentelemetry/sdk-node": "^0.220.0",
"@scarf/scarf": "^1.4.0",
"@types/diff": "^7.0.2",
"ai-tokenizer": "^1.0.6",
@@ -9931,6 +9931,514 @@
}
}
},
+ "node_modules/@librechat/agents/node_modules/@grpc/grpc-js": {
+ "version": "1.14.4",
+ "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.4.tgz",
+ "integrity": "sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@grpc/proto-loader": "^0.8.0",
+ "@js-sdsl/ordered-map": "^4.4.2"
+ },
+ "engines": {
+ "node": ">=12.10.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@grpc/proto-loader": {
+ "version": "0.8.1",
+ "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.8.1.tgz",
+ "integrity": "sha512-wtF6h+DY6M3YaDBPAmvuuA6jV8Sif9MjtOI5euKFWRgCDl5PeDpPsHR9u2l6St5ceY8AZgoNDww5+HvEsXFsGg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "lodash.camelcase": "^4.3.0",
+ "long": "^5.0.0",
+ "protobufjs": "^7.5.5",
+ "yargs": "^17.7.2"
+ },
+ "bin": {
+ "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/api-logs": {
+ "version": "0.220.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.220.0.tgz",
+ "integrity": "sha512-CmVa4ImJ+ynfrPMNaAXHET6Bhb44SwzmfyVJFq9ni2jgXJR/l7C6gfVFddNmHP+ZOkP9cf4f9DBe68qVLTHc9w==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/api": "^1.3.0"
+ },
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/configuration": {
+ "version": "0.220.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/configuration/-/configuration-0.220.0.tgz",
+ "integrity": "sha512-glfIVKnZevRin8fY/9uES/mhRtMT1lGINLHc9MIo5fTQZXswEEHamJtgjv4MTtzgnhHGC92mIS/0lzAUZMyE0w==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/core": "2.9.0",
+ "yaml": "^2.8.3"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.9.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/context-async-hooks": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/context-async-hooks/-/context-async-hooks-2.9.0.tgz",
+ "integrity": "sha512-OQ0vzvbZBiUhjqLnUaoNfYmP8553Crr3aggB4y0ZUi815mZ7idpdJXQmoKdeBKJelYttoBlLSSHubmyw3wvX4w==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": ">=1.0.0 <1.10.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/exporter-logs-otlp-grpc": {
+ "version": "0.220.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-grpc/-/exporter-logs-otlp-grpc-0.220.0.tgz",
+ "integrity": "sha512-s0sRPCSlXYqlgObOpCftomJllp3LfUL9FobQ5csg2172ydVhSEnu1ptpsVBJadazs5nUNp7vDuLE03FAFWTLOQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@grpc/grpc-js": "^1.14.3",
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/otlp-exporter-base": "0.220.0",
+ "@opentelemetry/otlp-grpc-exporter-base": "0.220.0",
+ "@opentelemetry/otlp-transformer": "0.220.0",
+ "@opentelemetry/sdk-logs": "0.220.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.3.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/exporter-logs-otlp-http": {
+ "version": "0.220.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-http/-/exporter-logs-otlp-http-0.220.0.tgz",
+ "integrity": "sha512-8186thl+pTw64iz/qEEen5oJZoZ/gO73XruChdaGlYdWOdBIQ42r+vHLf6a7vIDqTD4b8ZOoMlyxptanECaI9A==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/api-logs": "0.220.0",
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/otlp-exporter-base": "0.220.0",
+ "@opentelemetry/otlp-transformer": "0.220.0",
+ "@opentelemetry/sdk-logs": "0.220.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.3.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/exporter-logs-otlp-proto": {
+ "version": "0.220.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-proto/-/exporter-logs-otlp-proto-0.220.0.tgz",
+ "integrity": "sha512-8LZAxdJ0ENDAFwr4j0oY35mHBltiSzvlhdQAPGiC7p9VnxtuSq4SW1gfBAdW6t6hiQG6OwUl8w7KHaOdJPKHWg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/otlp-exporter-base": "0.220.0",
+ "@opentelemetry/otlp-transformer": "0.220.0",
+ "@opentelemetry/sdk-logs": "0.220.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.3.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/exporter-metrics-otlp-grpc": {
+ "version": "0.220.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-grpc/-/exporter-metrics-otlp-grpc-0.220.0.tgz",
+ "integrity": "sha512-U128izvJfX/dW9jRGP0gIfadR1Hg7ft3UEGIeRxLFK70m2BWw6AtNCOnsUygpw2zCgR/ygdWbGpcL6TmhW0ZGw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@grpc/grpc-js": "^1.14.3",
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/exporter-metrics-otlp-http": "0.220.0",
+ "@opentelemetry/otlp-exporter-base": "0.220.0",
+ "@opentelemetry/otlp-grpc-exporter-base": "0.220.0",
+ "@opentelemetry/otlp-transformer": "0.220.0",
+ "@opentelemetry/resources": "2.9.0",
+ "@opentelemetry/sdk-metrics": "2.9.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.3.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/exporter-metrics-otlp-http": {
+ "version": "0.220.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-http/-/exporter-metrics-otlp-http-0.220.0.tgz",
+ "integrity": "sha512-Yqt3RBw/bRVncaE9qIIhk4WfjbAQqXuP9FgAaU+IKPndnLEp/cUqZlSC324+bpmduRz7DoTjig8Ub0PeILWXUA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/otlp-exporter-base": "0.220.0",
+ "@opentelemetry/otlp-transformer": "0.220.0",
+ "@opentelemetry/resources": "2.9.0",
+ "@opentelemetry/sdk-metrics": "2.9.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.3.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/exporter-metrics-otlp-proto": {
+ "version": "0.220.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-proto/-/exporter-metrics-otlp-proto-0.220.0.tgz",
+ "integrity": "sha512-lyO+IQBdSvqHN/ZOW/OzrSWemtfD+HgWngn+HBNLhjy0YrCQQTz0OE/kSekH2Pl340dn9DWzhqHdz5Eftr+HLA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/exporter-metrics-otlp-http": "0.220.0",
+ "@opentelemetry/otlp-exporter-base": "0.220.0",
+ "@opentelemetry/otlp-transformer": "0.220.0",
+ "@opentelemetry/resources": "2.9.0",
+ "@opentelemetry/sdk-metrics": "2.9.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.3.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/exporter-prometheus": {
+ "version": "0.220.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-prometheus/-/exporter-prometheus-0.220.0.tgz",
+ "integrity": "sha512-JZD5DL/NBpVd2BHefvYosm3G40UZ/KzExLv5tc0eZe0CtrsHHtcOk3YPUxR2EINmUeBf8+w5UReTV8fFPn95lA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/resources": "2.9.0",
+ "@opentelemetry/sdk-metrics": "2.9.0",
+ "@opentelemetry/semantic-conventions": "^1.29.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.3.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/exporter-trace-otlp-grpc": {
+ "version": "0.220.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-grpc/-/exporter-trace-otlp-grpc-0.220.0.tgz",
+ "integrity": "sha512-bv1xmNhmNwIM6MdUBw4yYuJeVcEViVLk3uD69vOQMwueHBnfyl/u0HnBlB1FNY/Te0UOzJzvcbyR8wN6b+iGbA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@grpc/grpc-js": "^1.14.3",
+ "@opentelemetry/otlp-exporter-base": "0.220.0",
+ "@opentelemetry/otlp-grpc-exporter-base": "0.220.0",
+ "@opentelemetry/otlp-transformer": "0.220.0",
+ "@opentelemetry/sdk-trace": "2.9.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.3.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/exporter-trace-otlp-http": {
+ "version": "0.220.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-http/-/exporter-trace-otlp-http-0.220.0.tgz",
+ "integrity": "sha512-/+ExB3lRkf+erv4PnoywyL7RHKITidxtUpUTS55k7OQ0dB42S7gEF1gry7swb9MSm1hYLUhJg4QQh9W8SpwwqA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/otlp-exporter-base": "0.220.0",
+ "@opentelemetry/otlp-transformer": "0.220.0",
+ "@opentelemetry/resources": "2.9.0",
+ "@opentelemetry/sdk-trace": "2.9.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.3.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/exporter-trace-otlp-proto": {
+ "version": "0.220.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-proto/-/exporter-trace-otlp-proto-0.220.0.tgz",
+ "integrity": "sha512-voTAD8XgJxlK7zLkXh8EzMB09zrQr3tyY/BsnDTlDiQU/UdK58MZ63A3mUjdEDrxMjCVmBHU3WQJhRmQe+Dvzg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/otlp-exporter-base": "0.220.0",
+ "@opentelemetry/otlp-transformer": "0.220.0",
+ "@opentelemetry/resources": "2.9.0",
+ "@opentelemetry/sdk-trace": "2.9.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.3.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/exporter-zipkin": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-zipkin/-/exporter-zipkin-2.9.0.tgz",
+ "integrity": "sha512-RwINoce2BH8T4obT5pMcAla2sWma1YZvYuaktWmTluQ0PkQdvv5D060rWI1+kawX+J2qBRcMbwrZJJNcMJUauQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/resources": "2.9.0",
+ "@opentelemetry/sdk-trace": "2.9.0",
+ "@opentelemetry/semantic-conventions": "^1.29.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.0.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/instrumentation": {
+ "version": "0.220.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.220.0.tgz",
+ "integrity": "sha512-xQx3E2WxP1mDvKzxLxX+CTCtNLa560YJZ3087qYHerl2YmiKpv7AH+dAy7vmx+eVrZ5BwhfWUAVoKOoxCNHcpw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/api-logs": "0.220.0",
+ "import-in-the-middle": "^3.0.0",
+ "require-in-the-middle": "^8.0.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.3.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/otlp-exporter-base": {
+ "version": "0.220.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-exporter-base/-/otlp-exporter-base-0.220.0.tgz",
+ "integrity": "sha512-CXYo8UD5Mn9YbgebO2EL4wejtA+gxLmLiu6HCk2KH2BR7XhFN6/6p1UlCb23DYCjeYkndevLHuejCCN1yx4+OQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/otlp-transformer": "0.220.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.3.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/otlp-grpc-exporter-base": {
+ "version": "0.220.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-grpc-exporter-base/-/otlp-grpc-exporter-base-0.220.0.tgz",
+ "integrity": "sha512-/eIkBPMBTIvM3x/0mDX4aJeSkYifYClnBPr68PL1h5LV4VQv4+SV6CGrpiZ4fIWDnobVmhTWCm1J/QRdAWUfvA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@grpc/grpc-js": "^1.14.3",
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/otlp-exporter-base": "0.220.0",
+ "@opentelemetry/otlp-transformer": "0.220.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.3.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/otlp-transformer": {
+ "version": "0.220.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-transformer/-/otlp-transformer-0.220.0.tgz",
+ "integrity": "sha512-lXGrv7KXZ0gNH9SVNUaa6vv6phVYGvJxfXAlMbzbakiXru75f5MZl8Z7oqiMMQD77riVHJCFlQvbZs/VVN2/4A==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/api-logs": "0.220.0",
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/resources": "2.9.0",
+ "@opentelemetry/sdk-logs": "0.220.0",
+ "@opentelemetry/sdk-metrics": "2.9.0",
+ "@opentelemetry/sdk-trace": "2.9.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.3.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/propagator-b3": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/propagator-b3/-/propagator-b3-2.9.0.tgz",
+ "integrity": "sha512-WrOT1WsOUG+B7hstD2RYoMPIOK76G8E9AQHhMjUvrQaGx/oA7rPWQvvr1Rqv7+yy4R0ZMVwWLC4vW2xnkgWPAQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/core": "2.9.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": ">=1.0.0 <1.10.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/propagator-jaeger": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/propagator-jaeger/-/propagator-jaeger-2.9.0.tgz",
+ "integrity": "sha512-4mYGty27rYvSM0jtp1ZUOqd3LfVRCYg9H5G9OFzSx5HViYToU21MFhWfco7x1HwXr7ER8yGOiCIHZUwjPksc0Q==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/core": "2.9.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": ">=1.0.0 <1.10.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/resources": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.9.0.tgz",
+ "integrity": "sha512-jyA5MBLQ+Dkl3+JsZkUoUvL7yHvU64kLsvpXKarWm6347Sl1t1bXFTFykUePNpT5WH5pm9a2Qtt03iIYQhZ1Fg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/semantic-conventions": "^1.29.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": ">=1.3.0 <1.10.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/sdk-logs": {
+ "version": "0.220.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-logs/-/sdk-logs-0.220.0.tgz",
+ "integrity": "sha512-WywcTkQtv2iNmt+6y5Kcd4rzvx9bLVsBa2Nwcmg01IUaBTkTow3W4d9KE5vNBpEDtb9tp21WcRBY/lANRrApYA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/api-logs": "0.220.0",
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/resources": "2.9.0",
+ "@opentelemetry/semantic-conventions": "^1.29.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": ">=1.4.0 <1.10.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/sdk-metrics": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-2.9.0.tgz",
+ "integrity": "sha512-Xx8RGS4H5XEBl01WuCreMIpiah9cCXMbSkeuIePPdD2cUpq/vUzYmj8E/MK1OsbOc93FuAD4jfn2WOacKwLn7Q==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/resources": "2.9.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": ">=1.9.0 <1.10.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/sdk-node": {
+ "version": "0.220.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-node/-/sdk-node-0.220.0.tgz",
+ "integrity": "sha512-wHtGyHhSKHNH3fym33xRu4Ef/HXTFvX8eQ42xdQdEO9LYx9Y2qNyBDJytyqVlvmo6abWZlNYTUthuAGUMYqYnQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/api-logs": "0.220.0",
+ "@opentelemetry/configuration": "0.220.0",
+ "@opentelemetry/context-async-hooks": "2.9.0",
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/exporter-logs-otlp-grpc": "0.220.0",
+ "@opentelemetry/exporter-logs-otlp-http": "0.220.0",
+ "@opentelemetry/exporter-logs-otlp-proto": "0.220.0",
+ "@opentelemetry/exporter-metrics-otlp-grpc": "0.220.0",
+ "@opentelemetry/exporter-metrics-otlp-http": "0.220.0",
+ "@opentelemetry/exporter-metrics-otlp-proto": "0.220.0",
+ "@opentelemetry/exporter-prometheus": "0.220.0",
+ "@opentelemetry/exporter-trace-otlp-grpc": "0.220.0",
+ "@opentelemetry/exporter-trace-otlp-http": "0.220.0",
+ "@opentelemetry/exporter-trace-otlp-proto": "0.220.0",
+ "@opentelemetry/exporter-zipkin": "2.9.0",
+ "@opentelemetry/instrumentation": "0.220.0",
+ "@opentelemetry/otlp-exporter-base": "0.220.0",
+ "@opentelemetry/otlp-grpc-exporter-base": "0.220.0",
+ "@opentelemetry/propagator-b3": "2.9.0",
+ "@opentelemetry/propagator-jaeger": "2.9.0",
+ "@opentelemetry/resources": "2.9.0",
+ "@opentelemetry/sdk-logs": "0.220.0",
+ "@opentelemetry/sdk-metrics": "2.9.0",
+ "@opentelemetry/sdk-trace": "2.9.0",
+ "@opentelemetry/sdk-trace-base": "2.9.0",
+ "@opentelemetry/sdk-trace-node": "2.9.0",
+ "@opentelemetry/semantic-conventions": "^1.29.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": ">=1.3.0 <1.10.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/sdk-trace-base": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.9.0.tgz",
+ "integrity": "sha512-cp9zmTl62R8PJrpvFcmc8N2JQU/xfa0S+61q511Nji+QxCfZ8Ifvg7H27G8cANe4crg4RTrWsVvanHiXjSp6ag==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/resources": "2.9.0",
+ "@opentelemetry/sdk-trace": "2.9.0",
+ "@opentelemetry/semantic-conventions": "^1.29.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": ">=1.3.0 <1.10.0"
+ }
+ },
+ "node_modules/@librechat/agents/node_modules/@opentelemetry/sdk-trace-node": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-node/-/sdk-trace-node-2.9.0.tgz",
+ "integrity": "sha512-ec9a7ps37huy5itYk0MalaZdSLlM6AXWp/FhtEjgMpp5leEGojBDvAl/UWttQnkMZOvFHKzRESn8TD3yKTF5nQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/context-async-hooks": "2.9.0",
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/sdk-trace-base": "2.9.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": ">=1.0.0 <1.10.0"
+ }
+ },
"node_modules/@librechat/agents/node_modules/diff": {
"version": "9.0.0",
"resolved": "https://registry.npmjs.org/diff/-/diff-9.0.0.tgz",
@@ -9940,6 +10448,20 @@
"node": ">=0.3.1"
}
},
+ "node_modules/@librechat/agents/node_modules/import-in-the-middle": {
+ "version": "3.3.1",
+ "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-3.3.1.tgz",
+ "integrity": "sha512-0rymlHSFLwZ0ixx8DaQkoIyZojJPY2a0K2nEYslhKJ6jIYO/m0IcCb7iQsFPmS7WmKwISZiIrv5Icstrw/CmqA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "cjs-module-lexer": "^2.2.0",
+ "es-module-lexer": "^2.2.0",
+ "module-details-from-path": "^1.0.4"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/@librechat/agents/node_modules/openai": {
"version": "6.45.0",
"resolved": "https://registry.npmjs.org/openai/-/openai-6.45.0.tgz",
@@ -10528,9 +11050,9 @@
}
},
"node_modules/@opentelemetry/core": {
- "version": "2.7.1",
- "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.7.1.tgz",
- "integrity": "sha512-QAqIj32AtK6+pEVNG7EOVxHdE06RP+FM5qpiEJ4RtDcFIqKUZHYhl7/7UY5efhwmwNAg7j8QbJVBLxMerc0+gw==",
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.9.0.tgz",
+ "integrity": "sha512-m2nckMT80NnmjTYSPjJQObBJ+8dgkoajEOUbznL8AHZ3T3yHRk2P7gI1PhEBc1+lOnrYE9UWrWHqJDsmqjmNbw==",
"license": "Apache-2.0",
"dependencies": {
"@opentelemetry/semantic-conventions": "^1.29.0"
@@ -11003,21 +11525,6 @@
"@opentelemetry/api": "^1.3.0"
}
},
- "node_modules/@opentelemetry/instrumentation-http/node_modules/@opentelemetry/core": {
- "version": "2.2.0",
- "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.2.0.tgz",
- "integrity": "sha512-FuabnnUm8LflnieVxs6eP7Z383hgQU4W1e3KJS6aOG3RxWxcHyBxH8fDMHNgu/gFx/M2jvTOW/4/PHhLz6bjWw==",
- "license": "Apache-2.0",
- "dependencies": {
- "@opentelemetry/semantic-conventions": "^1.29.0"
- },
- "engines": {
- "node": "^18.19.0 || >=20.6.0"
- },
- "peerDependencies": {
- "@opentelemetry/api": ">=1.0.0 <1.10.0"
- }
- },
"node_modules/@opentelemetry/instrumentation-ioredis": {
"version": "0.55.0",
"resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-ioredis/-/instrumentation-ioredis-0.55.0.tgz",
@@ -11439,6 +11946,23 @@
"node": ">=18"
}
},
+ "node_modules/@opentelemetry/sdk-trace": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace/-/sdk-trace-2.9.0.tgz",
+ "integrity": "sha512-sGA19HvtrrSKYsseHphluH6j3p6Xa3fqc7c7y8f/7mYWejc1lyDFcpSdD1kYa50HCLUeEo4zA5bW0pniaPszuw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/resources": "2.9.0",
+ "@opentelemetry/semantic-conventions": "^1.29.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": ">=1.3.0 <1.10.0"
+ }
+ },
"node_modules/@opentelemetry/sdk-trace-base": {
"version": "2.7.1",
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.7.1.tgz",
@@ -11489,6 +12013,22 @@
"@opentelemetry/api": ">=1.0.0 <1.10.0"
}
},
+ "node_modules/@opentelemetry/sdk-trace/node_modules/@opentelemetry/resources": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.9.0.tgz",
+ "integrity": "sha512-jyA5MBLQ+Dkl3+JsZkUoUvL7yHvU64kLsvpXKarWm6347Sl1t1bXFTFykUePNpT5WH5pm9a2Qtt03iIYQhZ1Fg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/core": "2.9.0",
+ "@opentelemetry/semantic-conventions": "^1.29.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": ">=1.3.0 <1.10.0"
+ }
+ },
"node_modules/@opentelemetry/semantic-conventions": {
"version": "1.41.1",
"resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.41.1.tgz",
@@ -23766,6 +24306,12 @@
"node": ">= 0.4"
}
},
+ "node_modules/es-module-lexer": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.0.tgz",
+ "integrity": "sha512-KLdwQm2NvGLDkQDCGvmiQrhkd0JbMzXthwQAUgWjQuQdBLFa3eiBP5arXZyA+f8x+x7OXgud6bq2rxjGtHV2tw==",
+ "license": "MIT"
+ },
"node_modules/es-object-atoms": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.0.0.tgz",
@@ -42408,7 +42954,7 @@
"@azure/storage-blob": "^12.30.0",
"@google/genai": "^2.8.0",
"@keyv/redis": "^4.3.3",
- "@librechat/agents": "^3.2.57",
+ "@librechat/agents": "^3.2.61",
"@librechat/data-schemas": "*",
"@modelcontextprotocol/sdk": "^1.29.0",
"@opentelemetry/api": "^1.9.0",
diff --git a/package.json b/package.json
index d7bd425489..99154f516a 100644
--- a/package.json
+++ b/package.json
@@ -187,7 +187,8 @@
},
"svgo": "^2.8.2",
"js-yaml": "^4.2.0",
- "ws": "^8.21.0"
+ "ws": "^8.21.0",
+ "@opentelemetry/core": "^2.9.0"
},
"nodemonConfig": {
"ignore": [
diff --git a/packages/api/package.json b/packages/api/package.json
index 079f0d5464..bb4f40f02f 100644
--- a/packages/api/package.json
+++ b/packages/api/package.json
@@ -114,7 +114,7 @@
"@azure/storage-blob": "^12.30.0",
"@google/genai": "^2.8.0",
"@keyv/redis": "^4.3.3",
- "@librechat/agents": "^3.2.57",
+ "@librechat/agents": "^3.2.61",
"@librechat/data-schemas": "*",
"@modelcontextprotocol/sdk": "^1.29.0",
"@opentelemetry/api": "^1.9.0",
diff --git a/packages/api/src/agents/__tests__/load.spec.ts b/packages/api/src/agents/__tests__/load.spec.ts
index 705c5e8ef7..2604b5fe63 100644
--- a/packages/api/src/agents/__tests__/load.spec.ts
+++ b/packages/api/src/agents/__tests__/load.spec.ts
@@ -298,6 +298,97 @@ describe('loadAgent', () => {
expect(result?.model_parameters).not.toHaveProperty('promptPrefix');
});
+ test('should equip ask_user_question from the ephemeralAgent request flag', async () => {
+ const { EPHEMERAL_AGENT_ID } = Constants;
+
+ const result = await loadAgent(
+ {
+ req: {
+ user: { id: 'user123' },
+ body: {
+ ephemeralAgent: { ask_user_question: true } as TEphemeralAgent,
+ },
+ },
+ agent_id: EPHEMERAL_AGENT_ID as string,
+ endpoint: 'openai',
+ model_parameters: { model: 'gpt-4' } as unknown as AgentModelParameters,
+ },
+ deps,
+ );
+
+ expect(result?.tools).toContain('ask_user_question');
+ });
+
+ test('should equip ask_user_question from a model spec (askUserQuestion: true)', async () => {
+ const { EPHEMERAL_AGENT_ID } = Constants;
+
+ const result = await loadAgent(
+ {
+ req: {
+ user: { id: 'user123' },
+ body: {},
+ config: {
+ config: {},
+ fileStrategy: FileSources.local,
+ imageOutputType: 'png',
+ modelSpecs: {
+ list: [
+ {
+ name: 'asks-questions',
+ label: 'Asks Questions',
+ preset: { endpoint: 'openai', model: 'gpt-4' },
+ askUserQuestion: true,
+ },
+ {
+ name: 'no-questions',
+ label: 'No Questions',
+ preset: { endpoint: 'openai', model: 'gpt-4' },
+ },
+ ],
+ },
+ },
+ },
+ spec: 'asks-questions',
+ agent_id: EPHEMERAL_AGENT_ID as string,
+ endpoint: 'openai',
+ model_parameters: { model: 'gpt-4' } as unknown as AgentModelParameters,
+ },
+ deps,
+ );
+
+ expect(result?.tools).toContain('ask_user_question');
+
+ const withoutFlag = await loadAgent(
+ {
+ req: {
+ user: { id: 'user123' },
+ body: {},
+ config: {
+ config: {},
+ fileStrategy: FileSources.local,
+ imageOutputType: 'png',
+ modelSpecs: {
+ list: [
+ {
+ name: 'no-questions',
+ label: 'No Questions',
+ preset: { endpoint: 'openai', model: 'gpt-4' },
+ },
+ ],
+ },
+ },
+ },
+ spec: 'no-questions',
+ agent_id: EPHEMERAL_AGENT_ID as string,
+ endpoint: 'openai',
+ model_parameters: { model: 'gpt-4' } as unknown as AgentModelParameters,
+ },
+ deps,
+ );
+
+ expect(withoutFlag?.tools).not.toContain('ask_user_question');
+ });
+
test('should enable full skill scope for ephemeral model spec with skills true', async () => {
const { EPHEMERAL_AGENT_ID } = Constants;
@@ -628,6 +719,62 @@ describe('loadAgent', () => {
expect(result?.subagents).toEqual(subagents);
});
+ test('should equip ask_user_question for added agents from a model spec', async () => {
+ const result = await loadAddedAgent(
+ {
+ req: {
+ user: { id: 'user123' },
+ config: {
+ config: {},
+ fileStrategy: FileSources.local,
+ imageOutputType: 'png',
+ modelSpecs: {
+ list: [
+ {
+ name: 'added-asks',
+ label: 'Added Asks',
+ preset: { endpoint: 'openai', model: 'gpt-4' },
+ askUserQuestion: true,
+ },
+ ],
+ },
+ },
+ },
+ conversation: {
+ endpoint: 'openai',
+ model: 'gpt-4',
+ spec: 'added-asks',
+ } as unknown as TConversation,
+ },
+ deps,
+ );
+
+ expect(result?.tools).toContain('ask_user_question');
+ });
+
+ test('should equip ask_user_question for added agents from the ephemeralAgent flag', async () => {
+ const result = await loadAddedAgent(
+ {
+ req: {
+ user: { id: 'user123' },
+ config: {
+ config: {},
+ fileStrategy: FileSources.local,
+ imageOutputType: 'png',
+ },
+ },
+ conversation: {
+ endpoint: 'openai',
+ model: 'gpt-4',
+ ephemeralAgent: { ask_user_question: true },
+ } as unknown as TConversation,
+ },
+ deps,
+ );
+
+ expect(result?.tools).toContain('ask_user_question');
+ });
+
test('should handle ephemeral agent with undefined ephemeralAgent in body', async () => {
const { EPHEMERAL_AGENT_ID } = Constants;
diff --git a/packages/api/src/agents/__tests__/run-summarization.test.ts b/packages/api/src/agents/__tests__/run-summarization.test.ts
index ffb16cbbcf..b224c714dd 100644
--- a/packages/api/src/agents/__tests__/run-summarization.test.ts
+++ b/packages/api/src/agents/__tests__/run-summarization.test.ts
@@ -2006,3 +2006,234 @@ describe('HITL wiring is gated on hitlCapable', () => {
expect(config).not.toHaveProperty('humanInTheLoop');
});
});
+
+// ---------------------------------------------------------------------------
+// Suite: ask_user_question run wiring
+//
+// The ask tool pauses via a LangGraph `interrupt()` raised from its own body, so it
+// needs a durable checkpointer but NOT the tool-approval policy. It must be stripped
+// fail-closed from non-HITL callers (no resume surface) and from subagent child
+// configs (a child graph cannot pause the parent run).
+// ---------------------------------------------------------------------------
+describe('ask_user_question run wiring', () => {
+ const ASK = 'ask_user_question';
+ const askToolInstance = { name: ASK };
+ /** Approval policy NOT enabled — the ask tool must work without it. */
+ const plainAppConfig = {
+ config: {},
+ fileStrategy: FileSources.local,
+ imageOutputType: 'png',
+ endpoints: { [EModelEndpoint.agents]: {} },
+ } as unknown as AppConfig;
+
+ const runAndGetConfig = async (
+ agent: Record<string, unknown>,
+ extra: Record<string, unknown>,
+ ) => {
+ await createRun({
+ agents: [agent] as never,
+ signal: new AbortController().signal,
+ appConfig: plainAppConfig,
+ streaming: true,
+ streamUsage: true,
+ ...extra,
+ });
+ const createMock = Run.create as jest.Mock;
+ return createMock.mock.calls[0][0] as Record<string, unknown>;
+ };
+
+ const getCheckpointer = (config: Record<string, unknown>) =>
+ (config.graphConfig as { compileOptions?: { checkpointer?: unknown } }).compileOptions
+ ?.checkpointer;
+
+ const firstAgent = (config: Record<string, unknown>) =>
+ (config.graphConfig as { agents: Array<Record<string, unknown>> }).agents[0];
+
+ it('attaches the checkpointer WITHOUT humanInTheLoop when hitlCapable and the ask tool is present (approval disabled)', async () => {
+ const config = await runAndGetConfig(makeAgent({ tools: [askToolInstance] }), {
+ hitlCapable: true,
+ });
+ expect(config).not.toHaveProperty('humanInTheLoop');
+ expect(config).not.toHaveProperty('hooks');
+ expect(getCheckpointer(config)).toBeDefined();
+ const agent = firstAgent(config);
+ // The tool rides the in-graph direct path (graphTools) — never the
+ // event-dispatched surfaces, where interrupt() cannot pause the run.
+ expect((agent.graphTools as Array<{ name: string }>).map((t) => t.name)).toEqual([ASK]);
+ expect((agent.tools as Array<{ name: string }>).map((t) => t.name)).not.toContain(ASK);
+ });
+
+ it('detects the tool via toolRegistry / toolDefinitions too', async () => {
+ const viaRegistry = await runAndGetConfig(
+ makeAgent({ toolRegistry: new Map([[ASK, { name: ASK }]]) }),
+ { hitlCapable: true },
+ );
+ expect(getCheckpointer(viaRegistry)).toBeDefined();
+ jest.clearAllMocks();
+ const viaDefinitions = await runAndGetConfig(makeAgent({ toolDefinitions: [{ name: ASK }] }), {
+ hitlCapable: true,
+ });
+ expect(getCheckpointer(viaDefinitions)).toBeDefined();
+ });
+
+ it('strips the tool and attaches no checkpointer for a non-HITL caller', async () => {
+ const config = await runAndGetConfig(
+ makeAgent({
+ tools: [askToolInstance, { name: 'other_tool' }],
+ toolDefinitions: [{ name: ASK }, { name: 'other_tool' }],
+ toolRegistry: new Map([
+ [ASK, { name: ASK }],
+ ['other_tool', { name: 'other_tool' }],
+ ]),
+ }),
+ { hitlCapable: false },
+ );
+ expect(getCheckpointer(config)).toBeUndefined();
+ const agent = firstAgent(config);
+ expect((agent.tools as Array<{ name: string }>).map((t) => t.name)).toEqual(['other_tool']);
+ expect((agent.toolDefinitions as Array<{ name: string }>).map((d) => d.name)).toEqual([
+ 'other_tool',
+ ]);
+ expect((agent.toolRegistry as Map<string, unknown>).has(ASK)).toBe(false);
+ expect((agent.toolRegistry as Map<string, unknown>).has('other_tool')).toBe(true);
+ });
+
+ it('does not mutate the caller-owned toolRegistry when stripping (clone-before-mutate)', async () => {
+ const sharedRegistry = new Map([[ASK, { name: ASK }]]);
+ await runAndGetConfig(makeAgent({ toolRegistry: sharedRegistry }), { hitlCapable: false });
+ expect(sharedRegistry.has(ASK)).toBe(true);
+ });
+
+ it('strips the tool from subagent child configs even on an HITL-capable run', async () => {
+ const child = makeAgent({
+ id: 'agent_child',
+ name: 'Child',
+ tools: [askToolInstance],
+ toolDefinitions: [{ name: ASK }],
+ toolRegistry: new Map([[ASK, { name: ASK }]]),
+ });
+ const parent = makeAgent({
+ tools: [askToolInstance],
+ subagents: { enabled: true, allowSelf: false },
+ subagentAgentConfigs: [child],
+ });
+ const config = await runAndGetConfig(parent, { hitlCapable: true });
+ // Parent keeps the tool — as an in-graph direct tool — and gets the checkpointer…
+ expect((firstAgent(config).graphTools as Array<{ name: string }>).map((t) => t.name)).toEqual([
+ ASK,
+ ]);
+ expect(getCheckpointer(config)).toBeDefined();
+ // …the child copy is stripped everywhere, with no graphTools replacement.
+ const subagentConfigs = firstAgent(config).subagentConfigs as Array<{
+ agentInputs: Record<string, unknown>;
+ }>;
+ expect(subagentConfigs).toHaveLength(1);
+ const childInputs = subagentConfigs[0].agentInputs;
+ expect(childInputs.graphTools).toBeUndefined();
+ expect((childInputs.tools as Array<{ name: string }>).map((t) => t.name)).not.toContain(ASK);
+ expect((childInputs.toolDefinitions as Array<{ name: string }>).map((d) => d.name)).toEqual([]);
+ expect((childInputs.toolRegistry as Map<string, unknown>).has(ASK)).toBe(false);
+ });
+
+ it('a subagent-only ask tool attaches no checkpointer (top-level agents decide)', async () => {
+ const child = makeAgent({ id: 'agent_child', name: 'Child', tools: [askToolInstance] });
+ const parent = makeAgent({
+ subagents: { enabled: true, allowSelf: false },
+ subagentAgentConfigs: [child],
+ });
+ const config = await runAndGetConfig(parent, { hitlCapable: true });
+ expect(getCheckpointer(config)).toBeUndefined();
+ });
+
+ it('excludes ask_user_question from eager event tool execution', async () => {
+ const config = await runAndGetConfig(makeAgent(), { hitlCapable: true });
+ const eager = config.eagerEventToolExecution as { excludeToolNames: string[] };
+ expect(eager.excludeToolNames).toContain(ASK);
+ });
+
+ it('admin filteredTools is a real kill switch: strips the tool and blocks the checkpointer even on an HITL-capable run', async () => {
+ const filteredConfig = {
+ ...(plainAppConfig as unknown as Record<string, unknown>),
+ filteredTools: [ASK],
+ } as unknown as AppConfig;
+ await createRun({
+ agents: [
+ makeAgent({
+ tools: [askToolInstance],
+ toolDefinitions: [{ name: ASK }],
+ toolRegistry: new Map([[ASK, { name: ASK }]]),
+ }),
+ ] as never,
+ signal: new AbortController().signal,
+ appConfig: filteredConfig,
+ streaming: true,
+ streamUsage: true,
+ hitlCapable: true,
+ });
+ const config = (Run.create as jest.Mock).mock.calls[0][0] as Record<string, unknown>;
+ expect(getCheckpointer(config)).toBeUndefined();
+ const agent = firstAgent(config);
+ expect((agent.tools as Array<{ name: string }>).map((t) => t.name)).toEqual([]);
+ expect((agent.toolDefinitions as Array<{ name: string }>).map((d) => d.name)).toEqual([]);
+ expect((agent.toolRegistry as Map<string, unknown>).has(ASK)).toBe(false);
+ });
+
+ it('an includedTools allowlist disables the tool unless listed (allowlist precedence)', async () => {
+ const withoutTool = {
+ ...(plainAppConfig as unknown as Record<string, unknown>),
+ includedTools: ['calculator'],
+ } as unknown as AppConfig;
+ await createRun({
+ agents: [makeAgent({ tools: [askToolInstance] })] as never,
+ signal: new AbortController().signal,
+ appConfig: withoutTool,
+ streaming: true,
+ streamUsage: true,
+ hitlCapable: true,
+ });
+ let config = (Run.create as jest.Mock).mock.calls[0][0] as Record<string, unknown>;
+ expect(getCheckpointer(config)).toBeUndefined();
+ expect((firstAgent(config).tools as Array<{ name: string }>).map((t) => t.name)).toEqual([]);
+
+ jest.clearAllMocks();
+ const withTool = {
+ ...(plainAppConfig as unknown as Record<string, unknown>),
+ // includedTools wins over filteredTools — same precedence as loadAndFormatTools.
+ includedTools: [ASK],
+ filteredTools: [ASK],
+ } as unknown as AppConfig;
+ await createRun({
+ agents: [makeAgent({ tools: [askToolInstance] })] as never,
+ signal: new AbortController().signal,
+ appConfig: withTool,
+ streaming: true,
+ streamUsage: true,
+ hitlCapable: true,
+ });
+ config = (Run.create as jest.Mock).mock.calls[0][0] as Record<string, unknown>;
+ expect(getCheckpointer(config)).toBeDefined();
+ expect((firstAgent(config).graphTools as Array<{ name: string }>).map((t) => t.name)).toEqual([
+ ASK,
+ ]);
+ });
+
+ it('composes with the approval policy: both humanInTheLoop and the checkpointer attach', async () => {
+ const approvalConfig = {
+ config: {},
+ fileStrategy: FileSources.local,
+ imageOutputType: 'png',
+ endpoints: { [EModelEndpoint.agents]: { toolApproval: { enabled: true } } },
+ } as unknown as AppConfig;
+ await createRun({
+ agents: [makeAgent({ tools: [askToolInstance] })] as never,
+ signal: new AbortController().signal,
+ appConfig: approvalConfig,
+ streaming: true,
+ streamUsage: true,
+ hitlCapable: true,
+ });
+ const config = (Run.create as jest.Mock).mock.calls[0][0] as Record<string, unknown>;
+ expect(config.humanInTheLoop).toBeDefined();
+ expect(getCheckpointer(config)).toBeDefined();
+ });
+});
diff --git a/packages/api/src/agents/added.ts b/packages/api/src/agents/added.ts
index 8c54c9c6e3..cf07ce1ff1 100644
--- a/packages/api/src/agents/added.ts
+++ b/packages/api/src/agents/added.ts
@@ -9,6 +9,7 @@ import {
} from 'librechat-data-provider';
import type { Agent, TConversation, TModelSpec } from 'librechat-data-provider';
import type { AppConfig } from '@librechat/data-schemas';
+import { ASK_USER_QUESTION_TOOL_NAME } from '~/agents/hitl/askUserQuestionTool';
import { requiresEphemeralUserConnection } from '~/mcp/utils';
import { getCustomEndpointConfig } from '~/app/config';
@@ -117,6 +118,7 @@ export async function loadAddedAgent(
web_search?: boolean;
artifacts?: unknown;
memory?: boolean;
+ ask_user_question?: boolean;
}
| undefined;
@@ -184,6 +186,12 @@ export async function loadAddedAgent(
if (ephemeralAgent?.memory === true || modelSpec?.memory === true) {
tools.push(Tools.memory);
}
+ /** Mirror the primary ephemeral loader (`loadEphemeralAgent`) so a model
+ * spec's Ask User flag equips the added top-level agent too; downstream
+ * `createRun` gating (hitlCapable, non-subagent, admin filter) is uniform. */
+ if (ephemeralAgent?.ask_user_question === true || modelSpec?.askUserQuestion === true) {
+ tools.push(ASK_USER_QUESTION_TOOL_NAME);
+ }
const addedServers = new Set<string>();
for (const mcpServer of mcpServers) {
diff --git a/packages/api/src/agents/client.ts b/packages/api/src/agents/client.ts
index 4adf953bfb..e3cb6ff280 100644
--- a/packages/api/src/agents/client.ts
+++ b/packages/api/src/agents/client.ts
@@ -358,6 +358,16 @@ export function createTokenCounter(encoding: Parameters<typeof Tokenizer.getToke
}
export function logToolError(_graph: unknown, error: unknown, toolId: string): void {
+ /**
+ * A GraphInterrupt unwinding out of a tool body is the HITL pause working as
+ * designed (e.g. `ask_user_question` raising LangGraph `interrupt()`), not a
+ * tool failure — logging it as a Tool Error at error level is alarming noise.
+ * Name-based check: the class arrives from `@langchain/langgraph` inside
+ * `@librechat/agents`, so an instanceof against our own import can miss.
+ */
+ if ((error as Error | undefined)?.name === 'GraphInterrupt') {
+ return;
+ }
logAxiosError({
error,
message: `[api/server/controllers/agents/client.js #chatCompletion] Tool Error "${toolId}"`,
diff --git a/packages/api/src/agents/hitl/askUserQuestionTool.spec.ts b/packages/api/src/agents/hitl/askUserQuestionTool.spec.ts
new file mode 100644
index 0000000000..0d7a463e4b
--- /dev/null
+++ b/packages/api/src/agents/hitl/askUserQuestionTool.spec.ts
@@ -0,0 +1,132 @@
+import {
+ ASK_USER_QUESTION_TOOL_NAME,
+ AskUserQuestionToolDefinition,
+ askUserQuestionToolSchema,
+ createAskUserQuestionTool,
+} from './askUserQuestionTool';
+
+/**
+ * Contract-shape coverage. The runtime behavior (interrupt from the tool body,
+ * durable pause, answer round-trip over the real resume controller) is covered
+ * end-to-end in `api/server/controllers/agents/__tests__/askUserQuestion.e2e.spec.js`.
+ */
+describe('ask_user_question tool contract', () => {
+ test('the name matches the SDK interrupt discriminator the pipeline keys on', () => {
+ expect(ASK_USER_QUESTION_TOOL_NAME).toBe('ask_user_question');
+ expect(AskUserQuestionToolDefinition.name).toBe(ASK_USER_QUESTION_TOOL_NAME);
+ expect(createAskUserQuestionTool().name).toBe(ASK_USER_QUESTION_TOOL_NAME);
+ });
+
+ describe('zod schema (the wire shape the client card receives)', () => {
+ test('accepts a bare question', () => {
+ expect(askUserQuestionToolSchema.parse({ question: 'Deploy where?' })).toEqual({
+ question: 'Deploy where?',
+ });
+ });
+
+ test('accepts question + description + options', () => {
+ const input = {
+ question: 'Deploy where?',
+ description: 'Two environments are configured.',
+ options: [
+ { label: 'Staging', value: 'staging' },
+ { label: 'Production', value: 'production' },
+ ],
+ };
+ expect(askUserQuestionToolSchema.parse(input)).toEqual(input);
+ });
+
+ test('rejects an empty question', () => {
+ expect(askUserQuestionToolSchema.safeParse({ question: '' }).success).toBe(false);
+ });
+
+ test('rejects an over-cap question (model-generated text is bounded)', () => {
+ expect(askUserQuestionToolSchema.safeParse({ question: 'x'.repeat(2001) }).success).toBe(
+ false,
+ );
+ });
+
+ test('rejects more than 12 options', () => {
+ const options = Array.from({ length: 13 }, (_, i) => ({
+ label: `opt ${i}`,
+ value: `v${i}`,
+ }));
+ expect(askUserQuestionToolSchema.safeParse({ question: 'pick', options }).success).toBe(
+ false,
+ );
+ });
+
+ test('rejects an option missing label or value', () => {
+ expect(
+ askUserQuestionToolSchema.safeParse({
+ question: 'pick',
+ options: [{ label: 'only label' }],
+ }).success,
+ ).toBe(false);
+ expect(
+ askUserQuestionToolSchema.safeParse({
+ question: 'pick',
+ options: [{ label: '', value: 'v' }],
+ }).success,
+ ).toBe(false);
+ });
+
+ test('accepts multiSelect as an optional boolean and rejects other types', () => {
+ const input = {
+ question: 'Which apply?',
+ options: [
+ { label: 'A', value: 'a' },
+ { label: 'B', value: 'b' },
+ ],
+ multiSelect: true,
+ };
+ expect(askUserQuestionToolSchema.parse(input)).toEqual(input);
+ expect(
+ askUserQuestionToolSchema.safeParse({ question: 'pick', multiSelect: 'yes' }).success,
+ ).toBe(false);
+ });
+ });
+
+ describe('registry definition (schema-only twin)', () => {
+ test('question is required; options items require label + value', () => {
+ expect(AskUserQuestionToolDefinition.schema.required).toEqual(['question']);
+ expect(AskUserQuestionToolDefinition.schema.properties.options.items.required).toEqual([
+ 'label',
+ 'value',
+ ]);
+ });
+
+ test('multiSelect is declared as an optional boolean in both schemas', () => {
+ expect(AskUserQuestionToolDefinition.schema.properties.multiSelect.type).toBe('boolean');
+ expect(AskUserQuestionToolDefinition.schema.required).not.toContain('multiSelect');
+ expect(AskUserQuestionToolDefinition.description).toContain('multiSelect');
+ });
+
+ test('definition caps agree with the zod schema caps', () => {
+ const { properties } = AskUserQuestionToolDefinition.schema;
+ expect(
+ askUserQuestionToolSchema.safeParse({ question: 'x'.repeat(properties.question.maxLength) })
+ .success,
+ ).toBe(true);
+ expect(
+ askUserQuestionToolSchema.safeParse({
+ question: 'x'.repeat(properties.question.maxLength + 1),
+ }).success,
+ ).toBe(false);
+ const atCap = Array.from({ length: properties.options.maxItems }, (_, i) => ({
+ label: `l${i}`,
+ value: `v${i}`,
+ }));
+ expect(
+ askUserQuestionToolSchema.safeParse({ question: 'pick', options: atCap }).success,
+ ).toBe(true);
+ });
+
+ test('descriptions match between the instance, the definition, and the constant name', () => {
+ const instance = createAskUserQuestionTool();
+ expect(instance.description).toBe(AskUserQuestionToolDefinition.description);
+ expect(instance.description).toContain('exactly ONE question per turn');
+ expect(instance.description).toContain('NEVER call this tool in parallel');
+ });
+ });
+});
diff --git a/packages/api/src/agents/hitl/askUserQuestionTool.ts b/packages/api/src/agents/hitl/askUserQuestionTool.ts
new file mode 100644
index 0000000000..acf198b965
--- /dev/null
+++ b/packages/api/src/agents/hitl/askUserQuestionTool.ts
@@ -0,0 +1,207 @@
+import { z } from 'zod';
+import { askUserQuestion } from '@librechat/agents';
+import { tool } from '@librechat/agents/langchain/tools';
+import type { DynamicStructuredTool } from '@librechat/agents/langchain/tools';
+
+/**
+ * Tool name. Deliberately identical to the SDK's interrupt discriminator
+ * (`AskUserQuestionInterruptPayload.type === 'ask_user_question'`) and the client
+ * content-part type the merged question card renders — the whole pipeline keys on
+ * this one string.
+ */
+export const ASK_USER_QUESTION_TOOL_NAME = 'ask_user_question';
+
+/**
+ * Length caps double as the sanitization story: every one of these strings is
+ * model-generated and rendered verbatim (as text nodes — React escapes) in the
+ * client question card, so bound them here rather than trusting the model.
+ */
+const QUESTION_MAX = 2000;
+const DESCRIPTION_MAX = 4000;
+const OPTION_LABEL_MAX = 120;
+const OPTION_VALUE_MAX = 500;
+const OPTIONS_MAX = 12;
+
+const ASK_USER_QUESTION_DESCRIPTION = [
+ 'Ask the user a clarifying question and pause the run until they answer; their answer is',
+ "returned as this tool's result. Use it only when you are genuinely blocked on a decision",
+ 'you cannot resolve from the conversation or your other tools. Ask exactly ONE question per',
+ 'turn, and NEVER call this tool in parallel with any other tool call. When the realistic',
+ 'answers are enumerable, provide 2-6 concise options; set multiSelect to true only when',
+ 'several options may sensibly apply at once (the selected option values are returned joined',
+ 'by ", "). The user can always type a free-form answer instead — so do NOT include a',
+ "catch-all option like 'Other' or 'Something else': the answer UI always offers free-form",
+ 'input on its own.',
+].join(' ');
+
+/**
+ * Mirrors the SDK's `AskUserQuestionRequest` (question / description? / options?) — the
+ * validated input is passed to `askUserQuestion()` unchanged, so this schema IS the wire
+ * shape the client card receives inside the pendingAction payload.
+ */
+export const askUserQuestionToolSchema: z.ZodObject<
+ {
+ question: z.ZodString;
+ description: z.ZodOptional<z.ZodString>;
+ options: z.ZodOptional<
+ z.ZodArray<z.ZodObject<{ label: z.ZodString; value: z.ZodString }, 'strip'>, 'many'>
+ >;
+ multiSelect: z.ZodOptional<z.ZodBoolean>;
+ },
+ 'strip'
+> = z.object({
+ question: z
+ .string()
+ .min(1)
+ .max(QUESTION_MAX)
+ .describe('The single clarifying question to ask the user.'),
+ description: z
+ .string()
+ .max(DESCRIPTION_MAX)
+ .optional()
+ .describe('Optional context rendered alongside the question (why you are asking).'),
+ options: z
+ .array(
+ z.object({
+ label: z
+ .string()
+ .min(1)
+ .max(OPTION_LABEL_MAX)
+ .describe('Human-readable choice shown to the user.'),
+ value: z
+ .string()
+ .min(1)
+ .max(OPTION_VALUE_MAX)
+ .describe('Value returned as the answer if this option is picked.'),
+ }),
+ )
+ .max(OPTIONS_MAX)
+ .optional()
+ .describe(
+ 'Optional pre-defined choices (2-6 recommended). Omit to require a free-form answer.',
+ ),
+ multiSelect: z
+ .boolean()
+ .optional()
+ .describe('Allow the user to pick several options; their values are returned joined by ", ".'),
+});
+
+export type AskUserQuestionToolInput = z.infer<typeof askUserQuestionToolSchema>;
+
+/** Explicit shape of {@link AskUserQuestionToolDefinition} (isolatedDeclarations). */
+export interface AskUserQuestionToolDefinitionShape {
+ name: string;
+ description: string;
+ schema: {
+ type: 'object';
+ properties: {
+ question: { type: 'string'; minLength: number; maxLength: number; description: string };
+ description: { type: 'string'; maxLength: number; description: string };
+ options: {
+ type: 'array';
+ maxItems: number;
+ description: string;
+ items: {
+ type: 'object';
+ properties: {
+ label: { type: 'string'; minLength: number; maxLength: number; description: string };
+ value: { type: 'string'; minLength: number; maxLength: number; description: string };
+ };
+ required: string[];
+ };
+ };
+ multiSelect: { type: 'boolean'; description: string };
+ };
+ required: string[];
+ };
+}
+
+/**
+ * JSON-schema twin of {@link askUserQuestionToolSchema} for the schema-only tool
+ * registry (`agentToolDefinitions` in `tools/registry/definitions.ts`), same shape the
+ * Calculator/WebSearch builtin definitions use.
+ */
+export const AskUserQuestionToolDefinition: AskUserQuestionToolDefinitionShape = {
+ name: ASK_USER_QUESTION_TOOL_NAME,
+ description: ASK_USER_QUESTION_DESCRIPTION,
+ schema: {
+ type: 'object',
+ properties: {
+ question: {
+ type: 'string',
+ minLength: 1,
+ maxLength: QUESTION_MAX,
+ description: 'The single clarifying question to ask the user.',
+ },
+ description: {
+ type: 'string',
+ maxLength: DESCRIPTION_MAX,
+ description: 'Optional context rendered alongside the question (why you are asking).',
+ },
+ options: {
+ type: 'array',
+ maxItems: OPTIONS_MAX,
+ description:
+ 'Optional pre-defined choices (2-6 recommended). Omit to require a free-form answer.',
+ items: {
+ type: 'object',
+ properties: {
+ label: {
+ type: 'string',
+ minLength: 1,
+ maxLength: OPTION_LABEL_MAX,
+ description: 'Human-readable choice shown to the user.',
+ },
+ value: {
+ type: 'string',
+ minLength: 1,
+ maxLength: OPTION_VALUE_MAX,
+ description: 'Value returned as the answer if this option is picked.',
+ },
+ },
+ required: ['label', 'value'],
+ },
+ },
+ multiSelect: {
+ type: 'boolean',
+ description:
+ 'Allow the user to pick several options; their values are returned joined by ", ".',
+ },
+ },
+ required: ['question'],
+ },
+};
+
+/**
+ * Create the `ask_user_question` tool instance. The func calls the SDK's
+ * `askUserQuestion()` helper, which raises a LangGraph `interrupt()` — on the first
+ * pass execution unwinds (the run pauses; `run.getInterrupt().payload.type ===
+ * 'ask_user_question'`), and on the resume pass it returns the host-supplied
+ * `{ answer }`, which becomes the ToolMessage content the model sees.
+ *
+ * Requirements at the run level (wired in `agents/run.ts`): a checkpointer must be
+ * attached (the interrupt must be durable to be resumable) and the tool must be
+ * excluded from eager event execution (an interrupt raised outside the Pregel task
+ * frame cannot pause the run). It does NOT require the tool-approval policy
+ * (`humanInTheLoop`/hooks) — verified end-to-end in
+ * `api/server/controllers/agents/__tests__/askUserQuestion.e2e.spec.js`.
+ *
+ * LangGraph resume contract (documented on the SDK helper): the tool body re-runs
+ * from the top on the resume pass, and sibling tools in the same batch re-execute —
+ * which is why the description forbids parallel calls.
+ */
+export function createAskUserQuestionTool(): DynamicStructuredTool<
+ typeof askUserQuestionToolSchema
+> {
+ return tool(
+ async (input: AskUserQuestionToolInput) => {
+ const { answer } = askUserQuestion(input);
+ return answer;
+ },
+ {
+ name: ASK_USER_QUESTION_TOOL_NAME,
+ description: ASK_USER_QUESTION_DESCRIPTION,
+ schema: askUserQuestionToolSchema,
+ },
+ );
+}
diff --git a/packages/api/src/agents/hitl/index.ts b/packages/api/src/agents/hitl/index.ts
index 7ef769c8d3..2ff7b50b2d 100644
--- a/packages/api/src/agents/hitl/index.ts
+++ b/packages/api/src/agents/hitl/index.ts
@@ -3,3 +3,4 @@ export * from './runtime';
export * from './resume';
export * from './hooks';
export * from './hookLoader';
+export * from './askUserQuestionTool';
diff --git a/packages/api/src/agents/hitl/policy.spec.ts b/packages/api/src/agents/hitl/policy.spec.ts
index 3c6d0a79cb..fd064418e9 100644
--- a/packages/api/src/agents/hitl/policy.spec.ts
+++ b/packages/api/src/agents/hitl/policy.spec.ts
@@ -11,6 +11,7 @@ import {
sanitizeResumeModelParameters,
pickResumeContext,
applyResumeContext,
+ exemptAskUserQuestionFromApproval,
} from './policy';
describe('resolveToolApprovalPolicy', () => {
@@ -531,3 +532,22 @@ describe('pickResumeContext / applyResumeContext', () => {
expect(reloadedBody.promptPrefix).toBe('p');
});
});
+
+describe('exemptAskUserQuestionFromApproval', () => {
+ const NAME = 'ask_user_question';
+ it('adds the tool to allow when the admin did not mention it', () => {
+ expect(exemptAskUserQuestionFromApproval({ enabled: true }, NAME)?.allow).toEqual([NAME]);
+ expect(
+ exemptAskUserQuestionFromApproval({ enabled: true, allow: ['calculator'] }, NAME)?.allow,
+ ).toEqual(['calculator', NAME]);
+ });
+ it('respects explicit admin entries in any list', () => {
+ const asked = { enabled: true, ask: [NAME] };
+ expect(exemptAskUserQuestionFromApproval(asked, NAME)).toBe(asked);
+ const denied = { enabled: true, deny: [NAME] };
+ expect(exemptAskUserQuestionFromApproval(denied, NAME)).toBe(denied);
+ });
+ it('passes undefined through', () => {
+ expect(exemptAskUserQuestionFromApproval(undefined, NAME)).toBeUndefined();
+ });
+});
diff --git a/packages/api/src/agents/hitl/policy.ts b/packages/api/src/agents/hitl/policy.ts
index 1c65798f31..113884b1be 100644
--- a/packages/api/src/agents/hitl/policy.ts
+++ b/packages/api/src/agents/hitl/policy.ts
@@ -445,3 +445,29 @@ export function toClientPendingAction(
} = pendingAction;
return clientSafe;
}
+
+/**
+ * Exempt `ask_user_question` from the tool-approval prompt unless the admin
+ * mentioned it EXPLICITLY (in `allow`, `ask`, or `deny`). With approval enabled
+ * in its default prompt-everything mode, the ask tool would otherwise trigger
+ * an approval card for the act of asking a question — a double pause with no
+ * safety upside: the tool is side-effect-free by construction (it only asks;
+ * the payload is length-capped and rendered as text). An explicit admin entry
+ * still wins, in either direction.
+ */
+export function exemptAskUserQuestionFromApproval(
+ policy: TToolApprovalPolicy | undefined,
+ toolName: string,
+): TToolApprovalPolicy | undefined {
+ if (!policy) {
+ return policy;
+ }
+ const mentioned =
+ policy.allow?.includes(toolName) === true ||
+ policy.ask?.includes(toolName) === true ||
+ policy.deny?.includes(toolName) === true;
+ if (mentioned) {
+ return policy;
+ }
+ return { ...policy, allow: [...(policy.allow ?? []), toolName] };
+}
diff --git a/packages/api/src/agents/hitl/resume.spec.ts b/packages/api/src/agents/hitl/resume.spec.ts
index f164366cf7..b199cf2eab 100644
--- a/packages/api/src/agents/hitl/resume.spec.ts
+++ b/packages/api/src/agents/hitl/resume.spec.ts
@@ -5,6 +5,9 @@ import {
findUndecidedToolCalls,
findDisallowedDecisions,
findIncompleteDecisions,
+ createContentIndexOffsetHandlers,
+ attachAskUserQuestionAnswer,
+ attachAskUserQuestionArgs,
} from './resume';
describe('mapToolApprovalResolutions', () => {
@@ -169,3 +172,156 @@ describe('findIncompleteDecisions', () => {
).toEqual([]);
});
});
+
+describe('createContentIndexOffsetHandlers', () => {
+ const textSeed = (n: number) => Array.from({ length: n }, () => ({ type: 'text' }));
+ const makeRecorder = () => {
+ const calls: Array<{ event: string; data: unknown }> = [];
+ const handler = { handle: (event: string, data: unknown) => void calls.push({ event, data }) };
+ return { calls, handler };
+ };
+
+ it('returns the input untouched for offset 0 / undefined handlers', () => {
+ const { handler } = makeRecorder();
+ const handlers = { on_run_step: handler };
+ expect(createContentIndexOffsetHandlers(handlers, [])).toBe(handlers);
+ expect(createContentIndexOffsetHandlers(undefined, textSeed(3))).toBeUndefined();
+ });
+
+ it('shifts ON_RUN_STEP index by the offset without mutating the original payload', () => {
+ const { calls, handler } = makeRecorder();
+ const wrapped = createContentIndexOffsetHandlers({ on_run_step: handler }, textSeed(3))!;
+ const runStep = { id: 'step_1', index: 0, stepDetails: { type: 'message_creation' } };
+ wrapped.on_run_step.handle('on_run_step', runStep as never);
+ expect((calls[0].data as { index: number }).index).toBe(3);
+ expect(runStep.index).toBe(0); // caller's object untouched
+ });
+
+ it('shifts ON_AGENT_UPDATE nested index', () => {
+ const { calls, handler } = makeRecorder();
+ const wrapped = createContentIndexOffsetHandlers({ on_agent_update: handler }, textSeed(2))!;
+ wrapped.on_agent_update.handle('on_agent_update', {
+ agent_update: { index: 1, runId: 'r' },
+ } as never);
+ expect((calls[0].data as { agent_update: { index: number } }).agent_update.index).toBe(3);
+ });
+
+ it('passes every other event handler through by reference (stateful instances intact)', () => {
+ const { handler } = makeRecorder();
+ const deltaHandler = { handle: jest.fn() };
+ const wrapped = createContentIndexOffsetHandlers(
+ { on_run_step: handler, on_message_delta: deltaHandler },
+ textSeed(5),
+ )!;
+ expect(wrapped.on_message_delta).toBe(deltaHandler);
+ // Deltas carry no index — they resolve through the (shifted) stepMap entry.
+ wrapped.on_message_delta.handle('on_message_delta', { id: 'step_1', delta: {} } as never);
+ expect(deltaHandler.handle).toHaveBeenCalledTimes(1);
+ });
+
+ it('rebinds a resumed tool step to its seeded unresolved slot by tool_call id', () => {
+ const { calls, handler } = makeRecorder();
+ const seed = [
+ { type: 'text' },
+ { type: 'tool_call', tool_call: { id: 'tc_paused', output: '' } },
+ { type: 'tool_call', tool_call: { id: 'tc_done', output: 'already resolved' } },
+ ];
+ const wrapped = createContentIndexOffsetHandlers({ on_run_step: handler }, seed)!;
+
+ // The paused call's re-execution must land on its seeded slot (1), not 0+3.
+ wrapped.on_run_step.handle('on_run_step', {
+ id: 'step_t',
+ index: 0,
+ stepDetails: { type: 'tool_calls', tool_calls: [{ id: 'tc_paused' }] },
+ } as never);
+ expect((calls[0].data as { index: number }).index).toBe(1);
+
+ // Resolved seeded calls rebind too: ids are minted per call, so a same-id
+ // step can only be the interrupted batch re-executing (e.g. an ask part
+ // whose answer the resume controller pre-stamped onto the seed).
+ wrapped.on_run_step.handle('on_run_step', {
+ id: 'step_u',
+ index: 1,
+ stepDetails: { type: 'tool_calls', tool_calls: [{ id: 'tc_done' }] },
+ } as never);
+ expect((calls[1].data as { index: number }).index).toBe(2);
+
+ // Message steps always offset.
+ wrapped.on_run_step.handle('on_run_step', {
+ id: 'step_m',
+ index: 2,
+ stepDetails: { type: 'message_creation' },
+ } as never);
+ expect((calls[2].data as { index: number }).index).toBe(5);
+ });
+
+ it('leaves a runStep without a numeric index unshifted (defensive)', () => {
+ const { calls, handler } = makeRecorder();
+ const wrapped = createContentIndexOffsetHandlers({ on_run_step: handler }, textSeed(4))!;
+ const weird = { id: 'step_x' };
+ wrapped.on_run_step.handle('on_run_step', weird as never);
+ expect(calls[0].data).toBe(weird);
+ });
+});
+
+describe('attachAskUserQuestionAnswer', () => {
+ const question = { question: 'Which env?', options: [{ label: 'Staging', value: 'staging' }] };
+ const askPart = (output?: string) => ({
+ type: 'tool_call',
+ tool_call: {
+ id: 'tc1',
+ name: 'ask_user_question',
+ args: '',
+ ...(output != null && { output }),
+ },
+ });
+
+ it('stamps args (the authoritative question) and output (the answer) onto the last unanswered ask part', () => {
+ const content = [{ type: 'text' } as never, askPart()];
+ const next = attachAskUserQuestionAnswer(content as never, question as never, 'staging');
+ expect(next).not.toBe(content);
+ const patched = (next[1] as { tool_call: Record<string, unknown> }).tool_call;
+ expect(patched.output).toBe('staging');
+ expect(patched.progress).toBe(1);
+ expect(JSON.parse(patched.args as string)).toEqual(question);
+ // original untouched (pure)
+ expect((content[1] as { tool_call: { output?: string } }).tool_call.output).toBeUndefined();
+ });
+
+ it('skips already-answered ask parts and targets the newest unanswered one', () => {
+ const content = [askPart('earlier answer'), askPart()];
+ const next = attachAskUserQuestionAnswer(content as never, question as never, 'blue');
+ expect((next[0] as { tool_call: { output: string } }).tool_call.output).toBe('earlier answer');
+ expect((next[1] as { tool_call: { output: string } }).tool_call.output).toBe('blue');
+ });
+
+ it('returns the input array untouched when no ask part matches', () => {
+ const content = [{ type: 'text' } as never, askPart('done')];
+ expect(attachAskUserQuestionAnswer(content as never, question as never, 'x')).toBe(content);
+ });
+});
+
+describe('attachAskUserQuestionArgs (pause-time stamp)', () => {
+ const question = { question: 'Which env?' };
+ it('stamps args on the newest empty ask part, pure', () => {
+ const content = [
+ { type: 'tool_call', tool_call: { id: 'tc1', name: 'ask_user_question', args: '' } },
+ ];
+ const next = attachAskUserQuestionArgs(content as never, question as never);
+ expect(next).not.toBe(content);
+ expect(JSON.parse((next[0] as { tool_call: { args: string } }).tool_call.args)).toEqual(
+ question,
+ );
+ expect((content[0] as { tool_call: { args: string } }).tool_call.args).toBe('');
+ });
+ it('skips parts that already have args or an output', () => {
+ const withArgs = [
+ { type: 'tool_call', tool_call: { name: 'ask_user_question', args: '{"question":"x"}' } },
+ ];
+ expect(attachAskUserQuestionArgs(withArgs as never, question as never)).toBe(withArgs);
+ const answered = [
+ { type: 'tool_call', tool_call: { name: 'ask_user_question', args: '', output: 'done' } },
+ ];
+ expect(attachAskUserQuestionArgs(answered as never, question as never)).toBe(answered);
+ });
+});
diff --git a/packages/api/src/agents/hitl/resume.ts b/packages/api/src/agents/hitl/resume.ts
index 3f34331002..58b465221c 100644
--- a/packages/api/src/agents/hitl/resume.ts
+++ b/packages/api/src/agents/hitl/resume.ts
@@ -1,9 +1,12 @@
+import { GraphEvents } from '@librechat/agents';
import type {
ToolApprovalDecision,
ToolApprovalDecisionMap,
AskUserQuestionResolution,
+ EventHandler,
} from '@librechat/agents';
import type { Agents } from 'librechat-data-provider';
+import { ASK_USER_QUESTION_TOOL_NAME } from './askUserQuestionTool';
/**
* Translate the host-facing approval wire format into the SDK's resume value.
@@ -117,3 +120,187 @@ export function findIncompleteDecisions(
})
.map((r) => r.tool_call_id);
}
+
+/**
+ * Wrap a resume run's event handlers so every content index the rebuilt graph
+ * emits is shifted past the pre-pause content.
+ *
+ * WHY: a resumed run rebuilds the graph from the checkpoint, and the fresh
+ * graph assigns content indices from its own empty `contentData` — starting at
+ * 0. The host, meanwhile, seeds the (also fresh) content aggregator with the
+ * pre-pause parts, which occupy exactly those low indices. Without an offset
+ * the resumed model turn collides with the seed: when the types match at an
+ * index the new text silently MERGES into a pre-pause part, and when they
+ * don't (e.g. a reasoning/`think` part at index 0 with Anthropic models) every
+ * delta is dropped with `Content type mismatch` — the entire post-resume
+ * output vanishes from both the live stream and the saved message.
+ *
+ * The index enters the pipeline at exactly one point: `ON_RUN_STEP`'s payload
+ * (the `RunStep`, whose `index` every subsequent delta resolves through the
+ * aggregator's `stepMap`). `ON_AGENT_UPDATE` carries its own inline index and
+ * is offset likewise. All other handlers pass through untouched — same object
+ * references, so stateful handler instances keep working.
+ */
+export function createContentIndexOffsetHandlers(
+ handlers: Record<string, EventHandler> | undefined,
+ seedContent: Array<{ type?: string; tool_call?: { id?: string; output?: unknown } }> = [],
+): Record<string, EventHandler> | undefined {
+ const offset = seedContent.length;
+ if (handlers == null || !(offset > 0)) {
+ return handlers;
+ }
+
+ /**
+ * Resumed tool steps for calls the PAUSED turn already rendered must land
+ * back on their seeded slot — not a fresh offset slot — or the original
+ * part stays unresolved while a duplicate completed one appears after the
+ * seed (and its output never attaches). Map unresolved seeded tool_calls by
+ * id so the resume pass's re-execution (approval flows re-run the approved
+ * tool; ask re-runs its body) rebinds to the right index.
+ */
+ const seededToolCallIndex = new Map<string, number>();
+ seedContent.forEach((part, index) => {
+ const toolCall = part?.tool_call;
+ /**
+ * EVERY seeded id maps — including parts already carrying an output. Tool
+ * call ids are minted per call by the provider, so a resumed step bearing
+ * a seeded id can only be the interrupted batch re-executing (the resume
+ * controller pre-stamps the ask part's answer onto the seed, which must
+ * not exile its re-run step to a duplicate offset slot).
+ */
+ if (part?.type === 'tool_call' && typeof toolCall?.id === 'string') {
+ seededToolCallIndex.set(toolCall.id, index);
+ }
+ });
+
+ const wrapped: Record<string, EventHandler> = { ...handlers };
+
+ const runStepHandler = handlers[GraphEvents.ON_RUN_STEP];
+ if (runStepHandler) {
+ wrapped[GraphEvents.ON_RUN_STEP] = {
+ handle: (event, data, metadata, graph) => {
+ const runStep = data as
+ | {
+ index?: number;
+ stepDetails?: { type?: string; tool_calls?: Array<{ id?: string }> };
+ }
+ | undefined;
+ if (runStep == null || typeof runStep.index !== 'number') {
+ return runStepHandler.handle(event, data, metadata, graph);
+ }
+ const seededIndex =
+ runStep.stepDetails?.type === 'tool_calls'
+ ? runStep.stepDetails.tool_calls
+ ?.map((call) => (call.id ? seededToolCallIndex.get(call.id) : undefined))
+ .find((index) => index != null)
+ : undefined;
+ const shifted = {
+ ...runStep,
+ index: seededIndex ?? runStep.index + offset,
+ };
+ return runStepHandler.handle(event, shifted as typeof data, metadata, graph);
+ },
+ };
+ }
+
+ const agentUpdateHandler = handlers[GraphEvents.ON_AGENT_UPDATE];
+ if (agentUpdateHandler) {
+ wrapped[GraphEvents.ON_AGENT_UPDATE] = {
+ handle: (event, data, metadata, graph) => {
+ const update = data as { agent_update?: { index?: number } } | undefined;
+ const shifted =
+ update?.agent_update != null && typeof update.agent_update.index === 'number'
+ ? {
+ ...update,
+ agent_update: { ...update.agent_update, index: update.agent_update.index + offset },
+ }
+ : data;
+ return agentUpdateHandler.handle(event, shifted as typeof data, metadata, graph);
+ },
+ };
+ }
+
+ return wrapped;
+}
+
+/**
+ * Stamp the answered question onto the paused `ask_user_question` tool-call part
+ * before the resume run seeds it back into the content pipeline.
+ *
+ * WHY the part is otherwise empty: the streamed arg CHUNKS carry no tool name, and
+ * the aggregator only accepts name-less arg updates on the completion event — which
+ * never fires for this tool (the first pass interrupts mid-execution, and the
+ * rebuilt resume run has no step id to complete against). Saved messages therefore
+ * showed `args: ""` and no `output`, and the client rendered a "cancelled" tool.
+ * The authoritative data exists anyway: the pendingAction payload carries the full
+ * question, and the resume request carries the user's answer.
+ *
+ * Patches the LAST unanswered ask part (a re-pause targets the newest question;
+ * earlier ones already carry their answers). Pure — returns the input array when
+ * nothing matched.
+ */
+export function attachAskUserQuestionAnswer<
+ TPart extends { type?: string; tool_call?: { name?: string; output?: unknown } },
+>(content: TPart[], question: Agents.AskUserQuestionRequest, answer: string): TPart[] {
+ for (let i = content.length - 1; i >= 0; i--) {
+ const part = content[i];
+ const toolCall = part?.tool_call;
+ if (
+ part?.type !== 'tool_call' ||
+ toolCall?.name !== ASK_USER_QUESTION_TOOL_NAME ||
+ (typeof toolCall.output === 'string' && toolCall.output.length > 0)
+ ) {
+ continue;
+ }
+ const next = [...content];
+ next[i] = {
+ ...part,
+ tool_call: {
+ ...toolCall,
+ args: JSON.stringify(question),
+ output: answer,
+ progress: 1,
+ },
+ };
+ return next;
+ }
+ return content;
+}
+
+/**
+ * Stamp the question onto the paused `ask_user_question` tool-call part's args
+ * at PAUSE time (no answer yet). Companion to
+ * {@link attachAskUserQuestionAnswer}: an abandoned/expired/stopped pause never
+ * reaches the answer-resume stamp, and the streamed args were dropped by the
+ * aggregator (name-less chunks), so without this the persisted unfinished turn
+ * carries an empty ask part the record card can't render a question from.
+ * Targets the newest ask part with empty args and no output. Pure.
+ */
+export function attachAskUserQuestionArgs<
+ TPart extends {
+ type?: string;
+ tool_call?: { name?: string; args?: unknown; output?: unknown };
+ },
+>(content: TPart[], question: Agents.AskUserQuestionRequest): TPart[] {
+ for (let i = content.length - 1; i >= 0; i--) {
+ const part = content[i];
+ const toolCall = part?.tool_call;
+ const hasArgs =
+ (typeof toolCall?.args === 'string' && toolCall.args.trim().length > 0) ||
+ (toolCall?.args != null &&
+ typeof toolCall.args === 'object' &&
+ Object.keys(toolCall.args as object).length > 0);
+ if (
+ part?.type !== 'tool_call' ||
+ toolCall?.name !== ASK_USER_QUESTION_TOOL_NAME ||
+ hasArgs ||
+ (typeof toolCall.output === 'string' && toolCall.output.length > 0)
+ ) {
+ continue;
+ }
+ const next = [...content];
+ next[i] = { ...part, tool_call: { ...toolCall, args: JSON.stringify(question) } };
+ return next;
+ }
+ return content;
+}
diff --git a/packages/api/src/agents/load.ts b/packages/api/src/agents/load.ts
index 769f3f4ef6..a0192544da 100644
--- a/packages/api/src/agents/load.ts
+++ b/packages/api/src/agents/load.ts
@@ -13,6 +13,7 @@ import type {
Agent,
} from 'librechat-data-provider';
import type { AppConfig } from '@librechat/data-schemas';
+import { ASK_USER_QUESTION_TOOL_NAME } from '~/agents/hitl/askUserQuestionTool';
import { requiresEphemeralUserConnection } from '~/mcp/utils';
import { getCustomEndpointConfig } from '~/app/config';
@@ -76,6 +77,12 @@ export async function loadEphemeralAgent(
if (ephemeralAgent?.memory === true || modelSpec?.memory === true) {
tools.push(Tools.memory);
}
+ /** Same downstream gating as persisted agents applies: `createRun` only
+ * equips the tool when the request is HITL-capable, the agent is not a
+ * subagent, and the admin hasn't excluded it (filteredTools/includedTools). */
+ if (ephemeralAgent?.ask_user_question === true || modelSpec?.askUserQuestion === true) {
+ tools.push(ASK_USER_QUESTION_TOOL_NAME);
+ }
const addedServers = new Set<string>();
if (mcpServers.size > 0) {
diff --git a/packages/api/src/agents/run.ts b/packages/api/src/agents/run.ts
index f39a8479de..71f82ddec8 100644
--- a/packages/api/src/agents/run.ts
+++ b/packages/api/src/agents/run.ts
@@ -34,10 +34,14 @@ import type { BaseMessage } from '@librechat/agents/langchain/messages';
import type { AppConfig, IUser } from '@librechat/data-schemas';
import type { SubagentUsageEvent } from '~/agents/usage';
import type * as t from '~/types';
+import {
+ ASK_USER_QUESTION_TOOL_NAME,
+ createAskUserQuestionTool,
+} from '~/agents/hitl/askUserQuestionTool';
+import { resolveToolApprovalPolicy, exemptAskUserQuestionFromApproval } from '~/agents/hitl/policy';
import { getLLMConfig as getAnthropicLLMConfig } from '~/endpoints/anthropic/llm';
import { CREATE_FILE_TOOL_NAME, EDIT_FILE_TOOL_NAME } from '~/agents/tools';
import { getProviderConfig } from '~/endpoints/config/providers';
-import { resolveToolApprovalPolicy } from '~/agents/hitl/policy';
import { extractDefaultParams } from '~/endpoints/openai/llm';
import { resolveHeaders, createSafeUser } from '~/utils/env';
import { getAgentCheckpointer } from '~/agents/checkpointer';
@@ -730,6 +734,48 @@ function anyAgentHasCodeEnv(agents: RunAgent[]): boolean {
return false;
}
+/**
+ * Whether a single agent's tool surface includes the `ask_user_question` tool, in any
+ * of the three places a tool can live on a `RunAgent`: loaded instances (`tools`), the
+ * schema-only registry (`toolRegistry`), or serialized definitions (`toolDefinitions`).
+ * Checked against TOP-LEVEL agents only (not subagents — the tool is stripped from
+ * child configs in `buildAgentInput`, since a child graph executing outside the parent
+ * run's stream cannot pause the parent).
+ *
+ * Exported for AgentClient's pre-turn orphan-checkpoint prune gate: the prune must
+ * fire whenever THIS turn may attach a checkpointer, which since the ask tool is no
+ * longer coupled to `toolApproval.enabled` includes ask-capable runs.
+ */
+export function agentRequestsAskUserQuestion(agent: {
+ tools?: unknown[];
+ toolRegistry?: Map<string, unknown>;
+ toolDefinitions?: Array<{ name: string }>;
+}): boolean {
+ return (
+ agent.tools?.some(
+ (tool) => (tool as { name?: string } | undefined)?.name === ASK_USER_QUESTION_TOOL_NAME,
+ ) === true ||
+ agent.toolRegistry?.has(ASK_USER_QUESTION_TOOL_NAME) === true ||
+ agent.toolDefinitions?.some((def) => def.name === ASK_USER_QUESTION_TOOL_NAME) === true
+ );
+}
+
+/**
+ * Whether the admin tool filter (`includedTools` allowlist, else `filteredTools`
+ * exclude list — same precedence as `loadAndFormatTools`) disables
+ * `ask_user_question`. Enforced at RUN BUILD, not just in the tools-dialog listing:
+ * agents saved before an admin filtered the tool out would otherwise keep exposing
+ * it to the model, attaching checkpointers, and pausing runs — for a run-pausing
+ * tool the filter must be an actual kill switch.
+ */
+function isAskUserQuestionAdminDisabled(appConfig?: AppConfig): boolean {
+ const included = appConfig?.includedTools;
+ if (included != null && included.length > 0) {
+ return !included.includes(ASK_USER_QUESTION_TOOL_NAME);
+ }
+ return appConfig?.filteredTools?.includes(ASK_USER_QUESTION_TOOL_NAME) === true;
+}
+
/**
* Whether any agent reachable in the run — primary, handoff/parallel, or a
* nested subagent — opts into cross-turn `reasoning_content` reconstruction.
@@ -971,6 +1017,9 @@ export async function createRun({
}
}
+ /** Admin kill switch for the ask tool — see {@link isAskUserQuestionAdminDisabled}. */
+ const askToolAdminDisabled = isAskUserQuestionAdminDisabled(appConfig);
+
const buildAgentInput = (agent: RunAgent, opts: { isSubagent?: boolean } = {}): AgentInputs => {
const isSubagent = opts.isSubagent === true;
const provider =
@@ -1092,6 +1141,38 @@ export async function createRun({
toolDefinitions = toolDefinitions.map((def) => ({ ...def }));
}
+ /**
+ * `ask_user_question` pauses via a LangGraph `interrupt()` raised from its own
+ * tool body, so it must execute IN-PROCESS inside the graph's ToolNode — the
+ * event-dispatched path runs tool bodies in the host handler outside the Pregel
+ * task frame, where `interrupt()` throws and becomes an error ToolMessage. The
+ * tool therefore never rides the schema-only `toolDefinitions`/`toolRegistry`
+ * surfaces: on every path it is REMOVED from them (clone-before-mutate,
+ * matching the registry-clone discipline above), and on the one path where it
+ * can actually work — an HITL-capable caller's top-level agent, with the admin
+ * filter allowing it — a real instance is supplied via `graphTools`, the SDK's
+ * in-graph direct-tool seam (bound to the model, executed inside the task
+ * frame; requires `@librechat/agents` > 3.2.57, older versions ignore the
+ * field). Everywhere else (OpenAI-compatible + Responses controllers with no
+ * resume surface, subagent child graphs that compile without a checkpointer,
+ * admin-disabled) it is stripped fail-closed with no replacement.
+ */
+ let tools = agent.tools;
+ let askGraphTools: GenericTool[] | undefined;
+ if (agentRequestsAskUserQuestion(agent)) {
+ tools = tools?.filter(
+ (tool) => (tool as { name?: string } | undefined)?.name !== ASK_USER_QUESTION_TOOL_NAME,
+ );
+ toolDefinitions = toolDefinitions.filter((def) => def.name !== ASK_USER_QUESTION_TOOL_NAME);
+ if (toolRegistry?.has(ASK_USER_QUESTION_TOOL_NAME)) {
+ toolRegistry = new Map(toolRegistry);
+ toolRegistry.delete(ASK_USER_QUESTION_TOOL_NAME);
+ }
+ if (hitlCapable && !isSubagent && !askToolAdminDisabled) {
+ askGraphTools = [createAskUserQuestionTool() as unknown as GenericTool];
+ }
+ }
+
const effectiveMaxContextTokens = computeEffectiveMaxContextTokens(
summarization.reserveRatio,
agent.baseContextTokens,
@@ -1099,12 +1180,12 @@ export async function createRun({
);
const reasoningKey = getReasoningKey(provider, llmConfig, agent.endpoint, agent.reasoningKey);
- return {
+ const agentInput: AgentInputs = {
provider,
reasoningKey,
toolDefinitions,
agentId: agent.id,
- tools: agent.tools,
+ tools,
clientOptions: llmConfig,
instructions: systemContent,
additional_instructions: additionalInstructions || undefined,
@@ -1120,6 +1201,16 @@ export async function createRun({
contextPruningConfig: summarization.contextPruning,
maxToolResultChars: agent.maxToolResultChars,
};
+ if (askGraphTools) {
+ /**
+ * Typed structurally — not as `AgentInputs['graphTools']` — because the
+ * field ships in `@librechat/agents` > 3.2.57 (agents#289); older SDK
+ * versions ignore it at runtime (the tool is then simply absent, never
+ * broken). Inline the field in the literal once the dependency is bumped.
+ */
+ (agentInput as AgentInputs & { graphTools?: GenericTool[] }).graphTools = askGraphTools;
+ }
+ return agentInput;
};
const agentInputs: AgentInputs[] = [];
@@ -1195,14 +1286,32 @@ export async function createRun({
// normal final response / `[DONE]` with the tool call dangling. Only AgentClient (chat +
// resume) passes `hitlCapable`; without it the run is identical to the no-HITL path.
const hitl = hitlCapable
- ? buildHITLRunWiring(toolApprovalPolicy, {
- userId: user?.id,
- conversationId: requestBody?.conversationId,
- tenantId: tenantId ?? user?.tenantId,
- appConfig,
- })
+ ? buildHITLRunWiring(
+ // The ask tool is exempt from the approval prompt (unless explicitly
+ // listed by the admin) — approving the right to ask a question is a
+ // pure double-pause; the tool has no side effects to gate.
+ exemptAskUserQuestionFromApproval(toolApprovalPolicy, ASK_USER_QUESTION_TOOL_NAME),
+ {
+ userId: user?.id,
+ conversationId: requestBody?.conversationId,
+ tenantId: tenantId ?? user?.tenantId,
+ appConfig,
+ },
+ )
: undefined;
- if (hitl) {
+ /**
+ * The `ask_user_question` tool pauses via LangGraph `interrupt()` from inside its own
+ * body, which needs only a durable checkpointer — NOT the tool-approval policy
+ * (`humanInTheLoop`/hooks stay off unless approval is separately enabled; verified
+ * end-to-end in `api/.../agents/__tests__/askUserQuestion.e2e.spec.js`). Top-level
+ * check only: subagent copies of the tool are stripped in `buildAgentInput`. Gated on
+ * `hitlCapable` like approval, and the tool itself was stripped from non-HITL callers
+ * above, so a checkpointer here always has a resume surface. The LazyMongoSaver only
+ * persists when a run actually pauses, so attaching it is near-zero overhead.
+ */
+ const asksUserQuestions =
+ hitlCapable && !askToolAdminDisabled && agents.some(agentRequestsAskUserQuestion);
+ if (hitl || asksUserQuestions) {
const checkpointer = await getAgentCheckpointer(agentsEndpointConfig?.checkpointer);
graphConfig.compileOptions = { ...graphConfig.compileOptions, checkpointer };
}
@@ -1231,7 +1340,9 @@ export async function createRun({
// commits. create_file/edit_file write files; execute_code/bash_tool run
// code with large `code`/`command` args. `excludeToolNames` requires
// @librechat/agents with the eager-exclusion support (agents#281); older
- // versions ignore the field.
+ // versions ignore the field. ask_user_question raises a LangGraph
+ // `interrupt()` from its tool body, which must run inside the Pregel task
+ // frame — a speculative eager execution could never pause the run.
eagerEventToolExecution: {
enabled: true,
excludeToolNames: [
@@ -1239,6 +1350,7 @@ export async function createRun({
EDIT_FILE_TOOL_NAME,
Constants.EXECUTE_CODE,
Constants.BASH_TOOL,
+ ASK_USER_QUESTION_TOOL_NAME,
],
},
// Let host file-authoring tools share the code-execution sandbox session so
diff --git a/packages/api/src/stream/GenerationJobManager.ts b/packages/api/src/stream/GenerationJobManager.ts
index d6d34d8304..d8005e8c6b 100644
--- a/packages/api/src/stream/GenerationJobManager.ts
+++ b/packages/api/src/stream/GenerationJobManager.ts
@@ -763,8 +763,19 @@ class GenerationJobManagerClass {
* Cross-replica support (Redis mode):
* - Emits abort signal via Redis pub/sub
* - The replica running generation receives signal and aborts its AbortController
+ *
+ * `options.transformAbortContent` rewrites the persistable content BEFORE the
+ * final SSE is emitted (and before it is returned for the DB save), so a
+ * host-side stamp — e.g. re-attaching a paused `ask_user_question`'s args
+ * that the Redis chunk-log reconstruction dropped — reaches the LIVE client
+ * too, not just the saved message. Pure/optional; identity when omitted.
*/
- async abortJob(streamId: string): Promise<AbortResult> {
+ async abortJob(
+ streamId: string,
+ options?: {
+ transformAbortContent?: (content: TMessageContentParts[]) => TMessageContentParts[];
+ },
+ ): Promise<AbortResult> {
const jobData = await this.jobStore.getJob(streamId);
const runtime = this.runtimeState.get(streamId);
@@ -795,7 +806,12 @@ class GenerationJobManagerClass {
/** Content before clearing state */
const result = await this.jobStore.getContentParts(streamId);
const content = result?.content ?? [];
- const abortContent = filterPersistableAbortContent(content);
+ let abortContent = filterPersistableAbortContent(content);
+ if (options?.transformAbortContent) {
+ abortContent = options.transformAbortContent(
+ abortContent as TMessageContentParts[],
+ ) as typeof abortContent;
+ }
const shouldPersistAbortContent = abortContent.length > 0;
/** Collected usage for all models */
diff --git a/packages/api/src/tools/registry/definitions.ts b/packages/api/src/tools/registry/definitions.ts
index 5e953ce547..88973c079f 100644
--- a/packages/api/src/tools/registry/definitions.ts
+++ b/packages/api/src/tools/registry/definitions.ts
@@ -1,4 +1,5 @@
import { WebSearchToolDefinition, CalculatorToolDefinition } from '@librechat/agents';
+import { AskUserQuestionToolDefinition } from '~/agents/hitl/askUserQuestionTool';
import { geminiToolkit } from '~/tools/toolkits/gemini';
import { oaiToolkit } from '~/tools/toolkits/oai';
@@ -471,6 +472,12 @@ const agentToolDefinitions: Record<string, ToolRegistryDefinition> = {
schema: WebSearchToolDefinition.schema as unknown as ExtendedJsonSchema,
toolType: 'builtin',
},
+ [AskUserQuestionToolDefinition.name]: {
+ name: AskUserQuestionToolDefinition.name,
+ description: AskUserQuestionToolDefinition.description,
+ schema: AskUserQuestionToolDefinition.schema as ExtendedJsonSchema,
+ toolType: 'builtin',
+ },
};
export function getToolDefinition(toolName: string): ToolRegistryDefinition | undefined {
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index f130e465c6..5a753ab1ac 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -573,6 +573,7 @@ export enum AgentCapabilities {
context = 'context',
skills = 'skills',
memory = 'memory',
+ ask_user_question = 'ask_user_question',
tools = 'tools',
chain = 'chain',
ocr = 'ocr',
@@ -689,6 +690,7 @@ export const defaultAgentCapabilities = [
AgentCapabilities.context,
AgentCapabilities.skills,
AgentCapabilities.memory,
+ AgentCapabilities.ask_user_question,
AgentCapabilities.tools,
AgentCapabilities.chain,
AgentCapabilities.ocr,
diff --git a/packages/data-provider/src/models.ts b/packages/data-provider/src/models.ts
index b6f44dfef3..5249ac8f8f 100644
--- a/packages/data-provider/src/models.ts
+++ b/packages/data-provider/src/models.ts
@@ -53,6 +53,8 @@ export type TModelSpec = {
fileSearch?: boolean;
executeCode?: boolean;
memory?: boolean;
+ /** Equip the spec's ephemeral agent with the `ask_user_question` HITL tool. */
+ askUserQuestion?: boolean;
artifacts?: string | boolean;
mcpServers?: string[];
skills?: boolean | string[];
@@ -87,6 +89,7 @@ export const tModelSpecSchema = z.object({
fileSearch: z.boolean().optional(),
executeCode: z.boolean().optional(),
memory: z.boolean().optional(),
+ askUserQuestion: z.boolean().optional(),
artifacts: z.union([z.string(), z.boolean()]).optional(),
mcpServers: z.array(z.string()).optional(),
skills: z.union([z.boolean(), z.array(z.string())]).optional(),
diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.ts
index e5b7a5c3cc..e711a580a5 100644
--- a/packages/data-provider/src/types.ts
+++ b/packages/data-provider/src/types.ts
@@ -109,6 +109,8 @@ export type TEphemeralAgent = {
artifacts?: string;
skills?: boolean;
memory?: boolean;
+ /** Equip the ephemeral agent with the `ask_user_question` HITL tool. */
+ ask_user_question?: boolean;
};
export type TPayload = Partial<TMessage> &
diff --git a/packages/data-provider/src/types/agents.ts b/packages/data-provider/src/types/agents.ts
index 0e7463f924..eebcf80e0a 100644
--- a/packages/data-provider/src/types/agents.ts
+++ b/packages/data-provider/src/types/agents.ts
@@ -364,6 +364,9 @@ export namespace Agents {
/** Optional descriptive context for the prompt; mirrors the SDK field. */
description?: string;
options?: AskUserQuestionOption[];
+ /** When true the user may pick several options; the answer is their
+ * selected option values joined with ", ". */
+ multiSelect?: boolean;
}
/** Interrupt payload for an ask-user-question pause. */