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: Remember Tool Approvals Per Conversation (#16557)

Marco Berettafb1dd57a9b98
diff --git a/api/server/controllers/agents/__tests__/resume.spec.js b/api/server/controllers/agents/__tests__/resume.spec.js
index 653c3c78b9..4a50577d31 100644
--- a/api/server/controllers/agents/__tests__/resume.spec.js
+++ b/api/server/controllers/agents/__tests__/resume.spec.js
@@ -97,6 +97,7 @@ const mockCheckPermission = jest.fn();
const mockDecryptMetadata = jest.fn();
const mockStampConvoLastResponse = jest.fn().mockResolvedValue(undefined);
const mockStampForcedRetention = jest.fn().mockResolvedValue(undefined);
+const mockAddConvoToolApprovalAllows = jest.fn();
const mockDisposeClient = jest.fn();
const mockGetMCPRequestContext = jest.fn();
const mockCleanupMCPRequestContextForReq = jest.fn();
@@ -180,6 +181,7 @@ jest.mock('~/models', () => ({
settleAgentEventActorDetachedAction: (...args) =>
mockSettleAgentEventActorDetachedAction(...args),
stampConvoLastResponse: (...args) => mockStampConvoLastResponse(...args),
+ addConvoToolApprovalAllows: (...args) => mockAddConvoToolApprovalAllows(...args),
}));
jest.mock('~/server/services/Endpoints/agents/eventChildLease', () => ({
@@ -490,6 +492,29 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => {
...extra,
});
+ /** Enable "Always allow" and offer it on the paused `tc1` call. */
+ const withAllowAlways = (job) => {
+ requestConfigOverrides = {
+ endpoints: {
+ agents: {
+ checkpointer: { type: 'mongo' },
+ toolApproval: { enabled: true, allowAlways: true },
+ },
+ },
+ };
+ job.metadata.pendingAction.payload = {
+ type: 'tool_approval',
+ action_requests: [{ tool_call_id: 'tc1', name: 'search_mcp_github', arguments: {} }],
+ review_configs: [
+ { tool_call_id: 'tc1', allowed_decisions: ['approve', 'reject'], allow_always: true },
+ ],
+ };
+ mockAddConvoToolApprovalAllows.mockResolvedValue(true);
+ return job;
+ };
+ const allowAlwaysBody = () =>
+ approveBody({ decisions: [{ tool_call_id: 'tc1', decision: 'approve', scope: 'session' }] });
+
const configureEventActorResume = (expiredAt = new Date(Date.now() + 60_000)) => {
requestStateOverrides = {
_agentEventBindingParentConversationId: 'parent-conversation',
@@ -1370,6 +1395,17 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => {
expect(mockInitializeClient).not.toHaveBeenCalled();
});
+ it('does not remember an approval when the schedule fence rejects the resume', async () => {
+ mockGenerationJobManager.getJob.mockResolvedValue(withAllowAlways(makeScheduledJob()));
+ mockFinalizeScheduleResumeClaim.mockResolvedValue(false);
+
+ const res = await post(allowAlwaysBody());
+
+ expect(res.status).toBe(409);
+ expect(res.body).toMatchObject({ code: 'SCHEDULE_NO_LONGER_ACTIVE' });
+ expect(mockAddConvoToolApprovalAllows).not.toHaveBeenCalled();
+ });
+
it('settles a scheduled continuation stopped during its resumed segment', async () => {
const job = makeScheduledJob();
mockGenerationJobManager.getJob.mockResolvedValue(job);
@@ -2337,6 +2373,16 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => {
expect(mockInitializeClient).toHaveBeenCalled();
});
+ it('does not remember an approval when the project context fence rejects the resume', async () => {
+ withProject(4, 3);
+ const job = await mockGenerationJobManager.getJob();
+ mockGenerationJobManager.getJob.mockResolvedValue(withAllowAlways(job));
+ const res = await post(allowAlwaysBody());
+ expect(res.status).toBe(409);
+ expect(res.body).toMatchObject({ code: 'PROJECT_CONTEXT_CHANGED' });
+ expect(mockAddConvoToolApprovalAllows).not.toHaveBeenCalled();
+ });
+
it('rejects a resume whose Project no longer exists', async () => {
withProject(3, 3);
mockGetChatProject.mockResolvedValue(null);
@@ -2913,6 +2959,56 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => {
});
});
+ describe('remembered tool approvals', () => {
+ it('stores the approved tool only after the resume fences pass', async () => {
+ mockGenerationJobManager.getJob.mockResolvedValue(withAllowAlways(makeToolApprovalJob()));
+ const res = await post(allowAlwaysBody());
+ await settled;
+ expect(res.status).toBe(200);
+ expect(mockAddConvoToolApprovalAllows).toHaveBeenCalledWith({
+ user: USER_ID,
+ conversationId: CONVO_ID,
+ toolNames: ['search_mcp_github'],
+ max: 64,
+ });
+ expect(mockInitializeClient.mock.invocationCallOrder[0]).toBeLessThan(
+ mockAddConvoToolApprovalAllows.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('approves once without storing when a hook registered after the pause applies', async () => {
+ const { setPluginHookSource } = jest.requireActual('@librechat/api');
+ const hasToolApprovalHooks = jest.fn(() => true);
+ setPluginHookSource({ hasHooks: () => true, hasToolApprovalHooks, register: () => 0 });
+ try {
+ mockGenerationJobManager.getJob.mockResolvedValue(withAllowAlways(makeToolApprovalJob()));
+ const client = makeClient();
+ mockInitializeClient.mockResolvedValue({ client, userMCPAuthMap: {} });
+ const res = await post(allowAlwaysBody());
+ await settled;
+ await flush();
+ expect(res.status).toBe(200);
+ expect(hasToolApprovalHooks).toHaveBeenCalledWith(['search_mcp_github']);
+ expect(mockAddConvoToolApprovalAllows).not.toHaveBeenCalled();
+ expect(client.resumeCompletion).toHaveBeenCalledTimes(1);
+ } finally {
+ setPluginHookSource(undefined);
+ }
+ });
+
+ it('still resumes once when storing the remembered tool fails', async () => {
+ mockGenerationJobManager.getJob.mockResolvedValue(withAllowAlways(makeToolApprovalJob()));
+ mockAddConvoToolApprovalAllows.mockRejectedValue(new Error('db down'));
+ const client = makeClient();
+ mockInitializeClient.mockResolvedValue({ client, userMCPAuthMap: {} });
+ const res = await post(allowAlwaysBody());
+ await settled;
+ await flush();
+ expect(res.status).toBe(200);
+ expect(client.resumeCompletion).toHaveBeenCalledTimes(1);
+ });
+ });
+
describe('happy path: approve -> reconstruct -> resume -> finalize', () => {
const statefulCodeAgent = (bridgeWorkerId) => ({
id: AGENT_ID,
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js
index e7efd4ee99..63d615daed 100644
--- a/api/server/controllers/agents/client.js
+++ b/api/server/controllers/agents/client.js
@@ -59,6 +59,10 @@ const {
buildAttachedCodeEnvironmentAdmissionHooks,
resolveAttachedCodeApprovalMode,
markNativeCodeToolApprovalRequests,
+ markToolApprovalAllowAlways,
+ resolveRunToolApprovalAllows,
+ getRunMCPToolAliases,
+ collectAllowAlwaysAliases,
agentRunUsesCheckpointer,
canAgentGraphPause,
getPluginHookSource,
@@ -4385,7 +4389,26 @@ class AgentClient extends BaseClient {
]);
const interruptPayload =
interrupt.payload?.type === 'tool_approval'
- ? markNativeCodeToolApprovalRequests(interrupt.payload, reachableAgents)
+ ? markToolApprovalAllowAlways(
+ markNativeCodeToolApprovalRequests(interrupt.payload, reachableAgents),
+ {
+ policy: appConfig?.endpoints?.[EModelEndpoint.agents]?.toolApproval,
+ agents: reachableAgents,
+ aliases: getRunMCPToolAliases(run),
+ storedTools: resolveRunToolApprovalAllows(
+ appConfig?.endpoints?.[EModelEndpoint.agents]?.toolApproval,
+ this.options.req?.resolvedConversation,
+ this.conversationId,
+ ),
+ hookContext: {
+ userId: this.options.req?.user?.id,
+ conversationId: this.conversationId,
+ tenantId: resolveRequestTenantId(this.options.req ?? {}),
+ appConfig,
+ },
+ pluginHookSource: getPluginHookSource(),
+ },
+ )
: interrupt.payload;
const codeExecutionBinding =
interrupt.payload?.type === 'tool_approval' &&
@@ -4424,6 +4447,7 @@ class AgentClient extends BaseClient {
// so the server restores it and rebuilds the same graph (and the fingerprint matches).
resumeContext,
codeExecutionBinding,
+ toolApprovalAliases: collectAllowAlwaysAliases(interruptPayload, getRunMCPToolAliases(run)),
});
// Job-replacement guard: streamId == conversationId is reused per conversation, so a
@@ -4551,6 +4575,11 @@ class AgentClient extends BaseClient {
resolvedProgrammaticHooks: admissionToolApprovalHooks,
pluginHookSource: getPluginHookSource(),
askUserQuestionAdminDisabled,
+ toolApprovalAllows: resolveRunToolApprovalAllows(
+ agentsEConfig?.toolApproval,
+ this.options.req?.resolvedConversation,
+ this.conversationId,
+ ),
});
const runUsesCheckpointer = agentRunUsesCheckpointer({
policy: effectiveToolApprovalPolicy,
@@ -5001,6 +5030,11 @@ class AgentClient extends BaseClient {
// leave this off so an approval-gated tool can't pause where there's no resume path.
hitlCapable: true,
resolvedToolApprovalHooks,
+ toolApprovalAllows: resolveRunToolApprovalAllows(
+ agentsEConfig?.toolApproval,
+ this.options.req?.resolvedConversation,
+ this.conversationId,
+ ),
toolInputValidationErrors: this.toolInputValidationErrors,
// Mid-run steering: drain queued user messages at each tool-batch
// boundary and inject them into graph state. The offset wrapper
@@ -5788,6 +5822,11 @@ class AgentClient extends BaseClient {
// controller owns that lifecycle, so it must keep the HITL wiring on the rebuilt run.
hitlCapable: true,
resolvedToolApprovalHooks,
+ toolApprovalAllows: resolveRunToolApprovalAllows(
+ agentsEConfig?.toolApproval,
+ this.options.req?.resolvedConversation,
+ this.conversationId,
+ ),
// Plugin SessionStart hooks match on the lifecycle source; a rebuilt run is a
// resume, not a fresh startup.
sessionStartSource: 'resume',
diff --git a/api/server/controllers/agents/resume.js b/api/server/controllers/agents/resume.js
index 6608e8beb7..c7ec361c7e 100644
--- a/api/server/controllers/agents/resume.js
+++ b/api/server/controllers/agents/resume.js
@@ -14,6 +14,9 @@ const {
GENERATION_RECOVERY_FAILED_ERROR,
isPendingActionStale,
resolveToolApprovalResume,
+ recordToolApprovalAllows,
+ resolveRequestTenantId,
+ getPluginHookSource,
resolveAskUserQuestionResume,
buildResolvedAskUserQuestion,
appendResolvedAskUserQuestion,
@@ -68,6 +71,7 @@ const {
saveMessage,
getConvo,
getChatProject,
+ addConvoToolApprovalAllows,
getMessages,
getProjectFiles,
getFiles,
@@ -1965,11 +1969,12 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle)
});
client = result.client;
+ const reachableAgents = collectReachableAgents([
+ client.options?.agent,
+ ...(client.agentConfigs?.values() ?? []),
+ ]);
// Re-resolve the approved code target before provider/tool execution on this replica.
- assertCodeExecutionApprovalBinding(
- pendingAction.codeExecutionBinding,
- collectReachableAgents([client.options?.agent, ...(client.agentConfigs?.values() ?? [])]),
- );
+ assertCodeExecutionApprovalBinding(pendingAction.codeExecutionBinding, reachableAgents);
// Bind the rebuilt client to the in-flight turn's identity (no new user message).
client.conversationId = streamId;
@@ -2013,6 +2018,23 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle)
code: 'RUN_REPLACED',
});
}
+ await recordToolApprovalAllows({
+ userId,
+ conversationId,
+ policy: req.config?.endpoints?.[EModelEndpoint.agents]?.toolApproval,
+ pendingAction,
+ resolutions: req.body.decisions,
+ agents: reachableAgents,
+ hookContext: {
+ userId,
+ conversationId,
+ tenantId: resolveRequestTenantId(req),
+ appConfig: req.config,
+ },
+ pluginHookSource: getPluginHookSource(),
+ request: req,
+ addConvoToolApprovalAllows,
+ });
if (eventActorResumePromise == null) {
await resumeClient();
} else {
diff --git a/client/src/components/Chat/Messages/Content/ApprovalContext.tsx b/client/src/components/Chat/Messages/Content/ApprovalContext.tsx
index ed1bf597ea..aeae1ff74e 100644
--- a/client/src/components/Chat/Messages/Content/ApprovalContext.tsx
+++ b/client/src/components/Chat/Messages/Content/ApprovalContext.tsx
@@ -98,6 +98,8 @@ const ApprovalContext = createContext<ApprovalContextValue | null>(null);
export interface ToolApprovalDecisionDraft {
active: Agents.ToolApprovalDecisionType | null;
+ /** With `active === 'approve'`: also approve this tool for the rest of the conversation. */
+ allowAlways?: boolean;
editText: string;
responseText: string;
reason: string;
diff --git a/client/src/components/Chat/Messages/Content/ToolApproval.tsx b/client/src/components/Chat/Messages/Content/ToolApproval.tsx
index b71ad5e1d2..30e4aef15f 100644
--- a/client/src/components/Chat/Messages/Content/ToolApproval.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolApproval.tsx
@@ -1,6 +1,14 @@
import { useId, useContext, useEffect, useMemo } from 'react';
import { Button, TextareaAutosize } from '@librechat/client';
-import { Check, X, Pencil, MessageSquare, ShieldQuestion, TriangleAlert } from 'lucide-react';
+import {
+ X,
+ Check,
+ Pencil,
+ CheckCheck,
+ MessageSquare,
+ ShieldQuestion,
+ TriangleAlert,
+} from 'lucide-react';
import type { Agents } from 'librechat-data-provider';
import type { TranslationKeys } from '~/hooks';
import { useComposerPresentsApproval } from '~/components/Chat/approval/state';
@@ -90,10 +98,12 @@ export default function ToolApproval({
}) {
const localize = useLocalize();
const invalidJsonId = useId();
+ const allowAlwaysHintId = useId();
const { actionId, allowed_decisions: allowedDecisions, description } = approval;
const conversationId = useContext(ChatContext)?.conversation?.conversationId;
const composerPresents = useComposerPresentsApproval(conversationId, actionId);
const deferToComposer = surface === 'thread' && composerPresents;
+ const canAllowAlways = approval.allow_always === true && allowedDecisions.includes('approve');
const {
registerToolCall,
unregisterToolCall,
@@ -119,12 +129,14 @@ export default function ToolApproval({
: seedArgs(args);
const decisionDraft = getDecisionDraft(actionId, toolCallId) ?? {
active: initialDecision?.decision ?? null,
+ allowAlways: canAllowAlways && initialDecision?.scope === 'session',
editText: initialEditText,
responseText:
initialDecision?.decision === 'respond' ? (initialDecision.responseText ?? '') : '',
reason: initialDecision?.decision === 'reject' ? (initialDecision.reason ?? '') : '',
};
const { active, editText, responseText, reason } = decisionDraft;
+ const allowAlways = canAllowAlways && active === 'approve' && decisionDraft.allowAlways === true;
const updateDecisionDraft = (updates: Partial<typeof decisionDraft>) =>
setDecisionDraft(actionId, toolCallId, { ...decisionDraft, ...updates });
@@ -151,7 +163,11 @@ export default function ToolApproval({
return;
}
if (active === 'approve') {
- setDecision(actionId, toolCallId, { tool_call_id: toolCallId, decision: 'approve' });
+ setDecision(actionId, toolCallId, {
+ tool_call_id: toolCallId,
+ decision: 'approve',
+ ...(allowAlways && { scope: 'session' }),
+ });
return;
}
if (active === 'reject') {
@@ -187,7 +203,17 @@ export default function ToolApproval({
setDecision(actionId, toolCallId, null);
}
}
- }, [active, editText, responseText, reason, locked, setDecision, actionId, toolCallId]);
+ }, [
+ active,
+ allowAlways,
+ editText,
+ responseText,
+ reason,
+ locked,
+ setDecision,
+ actionId,
+ toolCallId,
+ ]);
const editIsValid = useMemo(() => {
if (active !== 'edit') {
@@ -248,14 +274,17 @@ export default function ToolApproval({
<div className="flex flex-wrap gap-2">
{allowedDecisions.map((decision) => {
const Icon = DECISION_ICON[decision];
+ const pressed = active === decision && (decision !== 'approve' || !allowAlways);
return (
<Button
key={decision}
size="sm"
- variant={active === decision ? 'default' : 'outline'}
+ variant={pressed ? 'default' : 'outline'}
disabled={locked}
- aria-pressed={active === decision}
- onClick={() => updateDecisionDraft({ active: active === decision ? null : decision })}
+ aria-pressed={pressed}
+ onClick={() =>
+ updateDecisionDraft({ active: pressed ? null : decision, allowAlways: false })
+ }
className="inline-flex items-center gap-1.5"
>
<Icon className="h-4 w-4" aria-hidden="true" />
@@ -263,7 +292,33 @@ export default function ToolApproval({
</Button>
);
})}
+ {canAllowAlways && (
+ <Button
+ size="sm"
+ variant={allowAlways ? 'default' : 'outline'}
+ disabled={locked}
+ aria-pressed={allowAlways}
+ aria-describedby={allowAlwaysHintId}
+ onClick={() =>
+ updateDecisionDraft({
+ active: allowAlways ? null : 'approve',
+ allowAlways: !allowAlways,
+ })
+ }
+ >
+ <CheckCheck className="h-4 w-4" aria-hidden="true" />
+ {localize('com_ui_approve_always')}
+ </Button>
+ )}
</div>
+ {canAllowAlways && (
+ <p
+ id={allowAlwaysHintId}
+ className={cn('text-text-secondary text-xs', !allowAlways && 'sr-only')}
+ >
+ {localize('com_ui_approve_always_hint')}
+ </p>
+ )}
{active === 'edit' && (
<div className="flex flex-col gap-1">
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolApproval.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolApproval.test.tsx
index 45f60ff99b..2d97d53dd8 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ToolApproval.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolApproval.test.tsx
@@ -7,8 +7,8 @@ import {
approvalPanelOpenFamily,
pendingApprovalActionFamily,
} from '~/components/Chat/approval/state';
+import ApprovalProvider, { useApprovalContext } from '../ApprovalContext';
import { ChatContext } from '~/Providers/ChatContext';
-import ApprovalProvider from '../ApprovalContext';
import ToolApproval from '../ToolApproval';
jest.mock('~/hooks', () => ({
@@ -18,6 +18,8 @@ jest.mock('~/hooks', () => ({
}
const map: Record<string, string> = {
com_ui_approve: 'Approve',
+ com_ui_approve_always: 'Always allow',
+ com_ui_approve_always_hint: 'Runs without asking for this conversation',
com_ui_reject: 'Reject',
com_ui_edit: 'Edit',
com_ui_respond: 'Respond',
@@ -55,7 +57,52 @@ const renderCards = (cards: React.ReactNode) =>
</RecoilRoot>,
);
+function DecisionProbe() {
+ const { getDecisions } = useApprovalContext();
+ return <output data-testid="decisions">{JSON.stringify(getDecisions('action-1'))}</output>;
+}
+
+const decisions = () => JSON.parse(screen.getByTestId('decisions').textContent ?? '[]');
+
describe('ToolApproval', () => {
+ test('hides Always allow unless the server offered it', () => {
+ renderCards(<ToolApproval approval={approval()} toolCallId="call-1" args={{}} />);
+ expect(screen.queryByRole('button', { name: 'Always allow' })).not.toBeInTheDocument();
+ });
+
+ test('Always allow submits a session-scoped approve and is mutually exclusive with Approve', () => {
+ renderCards(
+ <>
+ <ToolApproval
+ approval={{ ...approval(), allow_always: true }}
+ toolCallId="call-1"
+ args={{}}
+ />
+ <DecisionProbe />
+ </>,
+ );
+ const always = screen.getByRole('button', { name: 'Always allow' });
+ const approve = screen.getByRole('button', { name: 'Approve' });
+ expect(always).toHaveAccessibleDescription('Runs without asking for this conversation');
+
+ fireEvent.click(always);
+ expect(always).toHaveAttribute('aria-pressed', 'true');
+ expect(approve).toHaveAttribute('aria-pressed', 'false');
+ expect(decisions()).toEqual([
+ { tool_call_id: 'call-1', decision: 'approve', scope: 'session' },
+ ]);
+ expect(screen.getByRole('button', { name: 'Submit' })).toBeEnabled();
+
+ fireEvent.click(approve);
+ expect(always).toHaveAttribute('aria-pressed', 'false');
+ expect(approve).toHaveAttribute('aria-pressed', 'true');
+ expect(decisions()).toEqual([{ tool_call_id: 'call-1', decision: 'approve' }]);
+
+ fireEvent.click(always);
+ fireEvent.click(always);
+ expect(decisions()).toEqual([]);
+ });
+
test('enables Submit immediately after Approve is the first decision (#14390)', () => {
renderCards(<ToolApproval approval={approval()} toolCallId="call-1" args={{ a: 1 }} />);
diff --git a/client/src/components/Chat/approval/Review.tsx b/client/src/components/Chat/approval/Review.tsx
index 679b568b54..812aa2f0d4 100644
--- a/client/src/components/Chat/approval/Review.tsx
+++ b/client/src/components/Chat/approval/Review.tsx
@@ -158,6 +158,7 @@ export const PendingToolApprovalPanel = memo(function PendingToolApprovalPanel({
actionId: pendingAction.actionId,
allowed_decisions: config.allowed_decisions,
description: preview.description,
+ allow_always: config.allow_always === true,
}}
toolCallId={request.tool_call_id}
args={request.arguments}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 9c8012f2d8..f2a690778d 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -1172,6 +1172,8 @@
"com_ui_approval_expired": "This request expired or was already handled.",
"com_ui_approval_review_in_composer": "Review this request in the panel above the message box.",
"com_ui_approve": "Approve",
+ "com_ui_approve_always": "Always allow",
+ "com_ui_approve_always_hint": "This tool will run without asking for the rest of this conversation.",
"com_ui_archive": "Archive",
"com_ui_archive_all_error": "Failed to archive all chats",
"com_ui_archive_all_success": "All chats archived",
diff --git a/client/src/utils/approval.ts b/client/src/utils/approval.ts
index 2fb4f87440..ccd083257d 100644
--- a/client/src/utils/approval.ts
+++ b/client/src/utils/approval.ts
@@ -111,6 +111,7 @@ function tagApprovalOnPart(
actionId,
allowed_decisions: reviewConfig?.allowed_decisions ?? [],
description: request.description,
+ ...(reviewConfig?.allow_always === true && { allow_always: true }),
},
};
changed = true;
diff --git a/e2e/config/librechat.e2e.yaml b/e2e/config/librechat.e2e.yaml
index c7c2454fd7..e3b9dbaf59 100644
--- a/e2e/config/librechat.e2e.yaml
+++ b/e2e/config/librechat.e2e.yaml
@@ -147,6 +147,9 @@ endpoints:
toolApproval:
enabled: true
mode: bypass
+ # The probe below is an `ask` rule and a hook match, so it is never offered
+ # "Always allow"; the remembered-approval scenarios assert exactly that.
+ allowAlways: true
ask:
- approval_probe_mcp_e2e-memory
reason: E2E approval required before running {tool}.
diff --git a/e2e/specs/mock/scenarios/tool-allow-always.spec.ts b/e2e/specs/mock/scenarios/tool-allow-always.spec.ts
new file mode 100644
index 0000000000..c82ab5c33d
--- /dev/null
+++ b/e2e/specs/mock/scenarios/tool-allow-always.spec.ts
@@ -0,0 +1,269 @@
+import { randomUUID } from 'crypto';
+import { expect, test } from '@playwright/test';
+import type { APIRequestContext } from '@playwright/test';
+import type { RequestResult } from '../content-filters.helpers';
+import {
+ APPROVAL_REASON,
+ APPROVAL_TOOL_ID,
+ APPROVAL_PROMPT_MARKER,
+ uniqueLabel,
+ isResumeRequest,
+ composerApprovalPanel,
+ clearApprovalInvocations,
+ createAndSelectApprovalAgent,
+ expectApprovalInvocationCount,
+} from '../approvals.helpers';
+import { deleteConversations, deleteMessagesByConversation, withMongo } from '../db';
+import { cleanupAgent, closeMobileDrawer } from '../agents.helpers';
+import { loginAdmin, requestResult } from '../content-filters.helpers';
+import { MOCK_ENDPOINTS, messagesView, sendMessage } from '../helpers';
+
+/**
+ * The mock profile enables `toolApproval.allowAlways`, but the approval probe is the
+ * admin's `ask` rule and a programmatic hook's match. Both mean "always prompt", so the
+ * choice must never be offered for it, and a client that asks to remember it anyway must
+ * be refused without anything being stored on the conversation.
+ */
+
+const NO_PARENT = '00000000-0000-0000-0000-000000000000';
+const MCP_SERVER_TOOL_ID = 'sys__server__sys_mcp_e2e-memory';
+
+interface PendingAction {
+ actionId?: string;
+ conversationId?: string;
+ payload?: {
+ type?: string;
+ action_requests?: Array<{ tool_call_id?: string }>;
+ review_configs?: Array<{ tool_call_id?: string; allow_always?: boolean }>;
+ };
+}
+
+interface StatusResponse {
+ status?: string;
+ pendingAction?: PendingAction;
+}
+
+function expectStatus(result: RequestResult, status: number): void {
+ expect(result.status, result.text).toBe(status);
+}
+
+async function createApprovalAgent(request: APIRequestContext, token: string): Promise<string> {
+ const result = await requestResult(request, {
+ path: '/api/agents',
+ token,
+ method: 'POST',
+ data: {
+ name: `E2E Allow Always ${randomUUID()}`,
+ instructions: 'Use the requested approval probe tools and report their results.',
+ provider: MOCK_ENDPOINTS[0].label,
+ model: MOCK_ENDPOINTS[0].model,
+ tools: [MCP_SERVER_TOOL_ID, APPROVAL_TOOL_ID],
+ },
+ });
+ expectStatus(result, 201);
+ return (result.body as { id: string }).id;
+}
+
+async function startTurn(
+ request: APIRequestContext,
+ token: string,
+ agentId: string,
+ text: string,
+): Promise<string> {
+ const messageId = randomUUID();
+ const result = await requestResult(request, {
+ path: '/api/agents/chat/agents',
+ token,
+ method: 'POST',
+ data: {
+ text,
+ sender: 'User',
+ clientTimestamp: new Date().toISOString(),
+ isCreatedByUser: true,
+ parentMessageId: NO_PARENT,
+ conversationId: 'new',
+ clientRequestId: randomUUID(),
+ messageId,
+ responseMessageId: `${messageId}_response`,
+ endpoint: 'agents',
+ endpointType: 'agents',
+ agent_id: agentId,
+ files: [],
+ isTemporary: false,
+ isRegenerate: false,
+ error: false,
+ },
+ });
+ expectStatus(result, 200);
+ return (result.body as { conversationId: string }).conversationId;
+}
+
+async function readStatus(
+ request: APIRequestContext,
+ token: string,
+ conversationId: string,
+): Promise<StatusResponse | null> {
+ const result = await requestResult(request, {
+ path: `/api/agents/chat/status/${encodeURIComponent(conversationId)}`,
+ token,
+ });
+ if (result.status === 503) {
+ return null;
+ }
+ expectStatus(result, 200);
+ return result.body as StatusResponse;
+}
+
+async function waitForStatus(
+ request: APIRequestContext,
+ token: string,
+ conversationId: string,
+ status: string,
+): Promise<StatusResponse> {
+ let latest: StatusResponse | null = null;
+ await expect
+ .poll(
+ async () => {
+ latest = await readStatus(request, token, conversationId);
+ return latest?.status ?? 'pending';
+ },
+ { timeout: 30000, intervals: [100, 250, 500, 1000] },
+ )
+ .toBe(status);
+ return latest!;
+}
+
+async function resume(
+ request: APIRequestContext,
+ token: string,
+ agentId: string,
+ pending: PendingAction,
+ scope?: 'session',
+): Promise<RequestResult> {
+ return requestResult(request, {
+ path: '/api/agents/chat/resume',
+ token,
+ method: 'POST',
+ data: {
+ actionId: pending.actionId,
+ agent_id: agentId,
+ conversationId: pending.conversationId,
+ endpoint: 'agents',
+ endpointType: 'agents',
+ decisions: (pending.payload?.action_requests ?? []).map((action) => ({
+ tool_call_id: action.tool_call_id,
+ decision: 'approve',
+ ...(scope != null && { scope }),
+ })),
+ },
+ });
+}
+
+async function storedAllows(conversationId: string): Promise<unknown> {
+ return withMongo(async (db) => {
+ const convo = await db.collection('conversations').findOne({ conversationId });
+ return convo?.toolApprovalAllows ?? null;
+ });
+}
+
+test.describe('remembered tool approvals', () => {
+ test('a tool the admin always prompts for is not offered Always allow @scenario:always-allow-not-offered-for-admin-ask-tool', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ const label = uniqueLabel();
+ const value = `original-${label}`;
+ let agentId: string | undefined;
+ clearApprovalInvocations(value);
+
+ try {
+ agentId = await createAndSelectApprovalAgent(page);
+ await closeMobileDrawer(page);
+ await sendMessage(page, `${APPROVAL_PROMPT_MARKER}${label}`);
+ await expect(page).toHaveURL(/\/c\/(?!new)/, { timeout: 15000 });
+
+ const panel = composerApprovalPanel(page);
+ await expect(panel).toBeVisible({ timeout: 30000 });
+ await expect(panel).toContainText(APPROVAL_REASON);
+ await expect(panel.getByRole('button', { name: 'Approve' })).toBeVisible();
+ await expect(panel.getByRole('button', { name: 'Always allow' })).toHaveCount(0);
+ await expect(page.getByRole('button', { name: 'Always allow' })).toHaveCount(0);
+
+ await panel.getByRole('button', { name: 'Approve' }).click();
+ const [response] = await Promise.all([
+ page.waitForResponse((candidate) => isResumeRequest(candidate.request())),
+ panel.getByRole('button', { name: 'Continue', exact: true }).click(),
+ ]);
+ expect(response.status()).toBe(200);
+ const body = response.request().postDataJSON() as {
+ decisions?: Array<{ scope?: string }>;
+ };
+ expect(body.decisions?.every((decision) => decision.scope == null)).toBe(true);
+
+ await expect(
+ messagesView(page)
+ .getByText(/^E2E approval outcomes:/)
+ .last(),
+ ).toBeVisible({ timeout: 30000 });
+ await expectApprovalInvocationCount(value, 1);
+ } finally {
+ clearApprovalInvocations(value);
+ await cleanupAgent(page, agentId);
+ }
+ });
+
+ test('a request to remember a tool the pause did not offer is refused and nothing is stored @scenario:always-allow-unoffered-scope-refused', async ({
+ request,
+ }) => {
+ test.setTimeout(120000);
+ const token = await loginAdmin(request);
+ const label = uniqueLabel();
+ const value = `original-${label}`;
+ let agentId: string | undefined;
+ let conversationId: string | undefined;
+ clearApprovalInvocations(value);
+
+ try {
+ agentId = await createApprovalAgent(request, token);
+ conversationId = await startTurn(
+ request,
+ token,
+ agentId,
+ `${APPROVAL_PROMPT_MARKER}${label}`,
+ );
+ const paused = await waitForStatus(request, token, conversationId, 'requires_action');
+ const pending = paused.pendingAction!;
+ expect(pending.payload?.type).toBe('tool_approval');
+ expect(pending.payload?.review_configs?.length).toBeGreaterThan(0);
+ expect(pending.payload?.review_configs?.some((config) => config.allow_always)).toBe(false);
+
+ const forged = await resume(request, token, agentId, pending, 'session');
+ expectStatus(forged, 403);
+ expect(forged.body).toEqual(
+ expect.objectContaining({ error: 'Decision not permitted for one or more tools' }),
+ );
+ expect(await storedAllows(conversationId)).toBeNull();
+ await expectApprovalInvocationCount(value, 0);
+
+ // The refusal does not consume the pause: a one-time approval still runs the tool.
+ const approved = await resume(request, token, agentId, pending);
+ expectStatus(approved, 200);
+ await waitForStatus(request, token, conversationId, 'complete');
+ await expectApprovalInvocationCount(value, 1);
+ expect(await storedAllows(conversationId)).toBeNull();
+ } finally {
+ clearApprovalInvocations(value);
+ if (agentId != null) {
+ await requestResult(request, {
+ path: `/api/agents/${encodeURIComponent(agentId)}`,
+ token,
+ method: 'DELETE',
+ }).catch(() => undefined);
+ }
+ if (conversationId != null) {
+ await deleteMessagesByConversation([conversationId]);
+ await deleteConversations([conversationId]);
+ }
+ }
+ });
+});
diff --git a/librechat.example.yaml b/librechat.example.yaml
index 1753bb69e9..a338bf2b8a 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -905,6 +905,7 @@ endpoints:
# deny: ["mcp:*:delete_*"] # Deny rules always take precedence
# ask: ["mcp:*:*"]
# reason: "Review {tool} before it runs."
+ # allowAlways: false # Offer "Always allow" to stop prompting for a tool for the rest of a conversation
# # (optional) Persist Agent runs paused for approval or Ask User. MongoDB is the durable default.
# checkpointer:
# type: mongo # mongo (default) or memory (single-process development only)
diff --git a/packages/api/src/agents/hitl/admission.ts b/packages/api/src/agents/hitl/admission.ts
index 3f20d7c2f8..3e8ea9612d 100644
--- a/packages/api/src/agents/hitl/admission.ts
+++ b/packages/api/src/agents/hitl/admission.ts
@@ -2,14 +2,10 @@ import type { TToolApprovalPolicy } from 'librechat-data-provider';
import type { PluginHookSource } from '~/agents/hooks/source';
import type { MCPToolAlias } from '~/tools/classification';
import type { ResolvedToolApprovalHook } from './hooks';
-import {
- healToolApprovalPolicy,
- isHITLEnabled,
- isToolApprovalPauseCapable,
- isToolDeniedByApprovalPolicy,
-} from './policy';
+import { isHITLEnabled, isToolApprovalPauseCapable, isToolDeniedByApprovalPolicy } from './policy';
import { ASK_USER_QUESTION_TOOL_NAME } from './askUserQuestionTool';
import { resolvedToolApprovalHooksCanMatch } from './hooks';
+import { buildEffectiveToolApprovalPolicy } from './allow';
interface ApprovalToolReference {
readonly name?: string;
@@ -43,6 +39,8 @@ export interface ToolApprovalAdmissionInput {
readonly resolvedProgrammaticHooks?: readonly ResolvedToolApprovalHook[];
readonly pluginHookSource?: PluginHookSource;
readonly askUserQuestionAdminDisabled?: boolean;
+ /** Tools the conversation remembers; folded in exactly as `createRun` folds them. */
+ readonly toolApprovalAllows?: readonly string[];
}
function agentHasTool(agent: ToolApprovalAdmissionAgent, toolName: string): boolean {
@@ -99,6 +97,7 @@ export function canAgentGraphPause({
resolvedProgrammaticHooks = [],
pluginHookSource,
askUserQuestionAdminDisabled = false,
+ toolApprovalAllows,
}: ToolApprovalAdmissionInput): boolean {
const asksUserQuestion =
!askUserQuestionAdminDisabled &&
@@ -144,7 +143,7 @@ export function canAgentGraphPause({
}
}
- const effectivePolicy = healToolApprovalPolicy(policy, aliases);
+ const effectivePolicy = buildEffectiveToolApprovalPolicy(policy, aliases, toolApprovalAllows);
const knownToolCanPause = Array.from(toolOwners).some(([toolName, agentIds]) => {
const matcherNames = [toolName, ...(aliasesByToolName.get(toolName) ?? [])];
const pluginHookCanAsk = pluginHookSource?.hasToolApprovalHooks?.([toolName]) === true;
diff --git a/packages/api/src/agents/hitl/allow.spec.ts b/packages/api/src/agents/hitl/allow.spec.ts
new file mode 100644
index 0000000000..905dbd7453
--- /dev/null
+++ b/packages/api/src/agents/hitl/allow.spec.ts
@@ -0,0 +1,648 @@
+import { Constants, executeHooks, createToolPolicyHook } from '@librechat/agents';
+import type { Agents, TToolApprovalPolicy } from 'librechat-data-provider';
+import type { HookRegistry } from '@librechat/agents';
+import {
+ isToolAllowAlwaysEligible,
+ collectToolApprovalAllows,
+ recordToolApprovalAllows,
+ markToolApprovalAllowAlways,
+ applyConversationToolAllows,
+ resolveRunToolApprovalAllows,
+ collectAllowAlwaysAliases,
+ MAX_CONVERSATION_TOOL_ALLOWS,
+ buildEffectiveToolApprovalPolicy,
+} from './allow';
+import { registerToolApprovalHook, clearToolApprovalHooks } from './hooks';
+import { buildToolApprovalPayload, mapToolApprovalPolicy } from './policy';
+import { resolveToolApprovalResume } from './resume';
+import { canAgentGraphPause } from './admission';
+import { buildHITLRunWiring } from './runtime';
+
+const GITHUB_SEARCH = 'search_mcp_github';
+const GITLAB_SEARCH = 'search_mcp_gitlab';
+
+const enabled = (overrides: Partial<NonNullable<TToolApprovalPolicy>> = {}) => ({
+ enabled: true,
+ allowAlways: true,
+ ...overrides,
+});
+
+/** Run the SDK's real policy evaluation for one tool name. */
+async function decide(policy: TToolApprovalPolicy | undefined, toolName: string) {
+ const hook = createToolPolicyHook(mapToolApprovalPolicy(policy) ?? {});
+ const result = await hook(
+ {
+ hook_event_name: 'PreToolUse',
+ runId: 'run',
+ toolName,
+ toolInput: {},
+ toolUseId: 'call',
+ } as Parameters<typeof hook>[0],
+ new AbortController().signal,
+ );
+ return result.decision;
+}
+
+const payloadFor = (...names: string[]): Agents.ToolApprovalInterruptPayload =>
+ buildToolApprovalPayload(
+ names.map((name, index) => ({ name, arguments: {}, tool_call_id: `call-${index}` })),
+ );
+
+describe('server enforcement of conversation tool allows', () => {
+ it('auto-approves only the exact remembered tool, not a same-named tool from another server', async () => {
+ const policy = applyConversationToolAllows(enabled(), [GITHUB_SEARCH]);
+ expect(await decide(policy, GITHUB_SEARCH)).toBe('allow');
+ expect(await decide(policy, GITLAB_SEARCH)).toBe('ask');
+ expect(await decide(policy, 'search')).toBe('ask');
+ });
+
+ it('never lets a remembered tool beat an admin deny or ask rule', async () => {
+ const policy = applyConversationToolAllows(
+ enabled({ deny: ['*_mcp_github'], ask: ['delete_*'] }),
+ [GITHUB_SEARCH, 'delete_repo'],
+ );
+ expect(await decide(policy, GITHUB_SEARCH)).toBe('deny');
+ expect(await decide(policy, 'delete_repo')).toBe('ask');
+ });
+
+ it('ignores stored tools when the feature is off, HITL is off, or mode is dontAsk', async () => {
+ for (const policy of [
+ enabled({ allowAlways: false }),
+ { ...enabled(), enabled: false },
+ enabled({ mode: 'dontAsk' as const }),
+ ]) {
+ const applied = applyConversationToolAllows(policy, [GITHUB_SEARCH]);
+ expect(applied).toBe(policy);
+ }
+ expect(await decide(enabled({ allowAlways: false }), GITHUB_SEARCH)).toBe('ask');
+ });
+
+ it('drops stored wildcards and native code tools instead of widening them', async () => {
+ const policy = applyConversationToolAllows(enabled(), ['*', Constants.BASH_TOOL]);
+ expect(policy?.allow).toBeUndefined();
+ expect(await decide(policy, 'anything')).toBe('ask');
+ });
+
+ it('resolves run allows only from the stored record of the executing conversation', () => {
+ const convo = { conversationId: 'c1', toolApprovalAllows: [GITHUB_SEARCH, 42] };
+ expect(resolveRunToolApprovalAllows(enabled(), convo, 'c1')).toEqual([GITHUB_SEARCH]);
+ expect(resolveRunToolApprovalAllows(enabled(), convo, 'c2')).toEqual([]);
+ expect(resolveRunToolApprovalAllows(enabled({ allowAlways: false }), convo, 'c1')).toEqual([]);
+ });
+});
+
+describe('isToolAllowAlwaysEligible', () => {
+ it('rejects deny/ask matches, wildcards, empty and oversized names', () => {
+ const policy = enabled({ deny: ['rm_*'], ask: ['pay'] });
+ expect(isToolAllowAlwaysEligible(policy, GITHUB_SEARCH)).toBe(true);
+ expect(isToolAllowAlwaysEligible(policy, 'rm_rf')).toBe(false);
+ expect(isToolAllowAlwaysEligible(policy, 'pay')).toBe(false);
+ expect(isToolAllowAlwaysEligible(policy, 'a*')).toBe(false);
+ expect(isToolAllowAlwaysEligible(policy, '')).toBe(false);
+ expect(isToolAllowAlwaysEligible(policy, 'x'.repeat(300))).toBe(false);
+ expect(isToolAllowAlwaysEligible(policy, Constants.EXECUTE_CODE)).toBe(false);
+ });
+});
+
+describe('markToolApprovalAllowAlways', () => {
+ it('offers the choice only for eligible tools that can be approved', () => {
+ const payload = payloadFor(GITHUB_SEARCH, 'pay');
+ const marked = markToolApprovalAllowAlways(payload, { policy: enabled({ ask: ['pay'] }) });
+ expect(marked.review_configs.map((config) => config.allow_always)).toEqual([true, undefined]);
+ });
+
+ it('does not offer the choice for a tool a healed ask rule matches by its other spelling', () => {
+ const payload = payloadFor(GITHUB_SEARCH);
+ const policy = enabled({ ask: ['legacy_search_mcp_github'] });
+ const agents = [
+ { mcpToolAliases: [{ name: GITHUB_SEARCH, aliasName: 'legacy_search_mcp_github' }] },
+ ];
+ expect(markToolApprovalAllowAlways(payload, { policy }).review_configs[0].allow_always).toBe(
+ true,
+ );
+ expect(markToolApprovalAllowAlways(payload, { policy, agents })).toBe(payload);
+ });
+
+ it('heals against aliases the run discovered after its agents were collected', () => {
+ const payload = payloadFor(GITHUB_SEARCH);
+ const policy = enabled({ ask: ['legacy_search_mcp_github'] });
+ const aliases = [{ name: GITHUB_SEARCH, aliasName: 'legacy_search_mcp_github' }];
+ expect(markToolApprovalAllowAlways(payload, { policy, agents: [{}], aliases })).toBe(payload);
+ });
+
+ it('stops offering new tools once the configured cap is reached', () => {
+ const payload = payloadFor(GITHUB_SEARCH, GITLAB_SEARCH, GITHUB_SEARCH);
+ const policy = enabled({ allowAlwaysMaxTools: 2 });
+ const offers = (storedTools: string[]) =>
+ markToolApprovalAllowAlways(payload, { policy, storedTools }).review_configs.map(
+ (config) => config.allow_always,
+ );
+ expect(offers([])).toEqual([true, true, true]);
+ expect(offers(['other'])).toEqual([true, undefined, true]);
+ expect(offers(['other', 'another'])).toEqual([undefined, undefined, undefined]);
+ // A tool already remembered costs no room, so it is still offered at the cap.
+ expect(offers(['other', GITLAB_SEARCH])).toEqual([undefined, true, undefined]);
+ });
+
+ it('counts only the stored prefix the run honors after the cap is lowered', () => {
+ const payload = payloadFor(GITHUB_SEARCH);
+ const policy = enabled({ allowAlwaysMaxTools: 1 });
+ const storedTools = ['other', GITHUB_SEARCH];
+ expect(applyConversationToolAllows(policy, storedTools)?.allow).toEqual(['other']);
+ expect(markToolApprovalAllowAlways(payload, { policy, storedTools })).toBe(payload);
+ });
+
+ it('uses the configured tool name length cap', () => {
+ const policy = enabled({ allowAlwaysMaxToolNameLength: 8 });
+ expect(isToolAllowAlwaysEligible(policy, 'short')).toBe(true);
+ expect(isToolAllowAlwaysEligible(policy, GITHUB_SEARCH)).toBe(false);
+ expect(isToolAllowAlwaysEligible(enabled(), 'x'.repeat(256))).toBe(true);
+ expect(isToolAllowAlwaysEligible(enabled(), 'x'.repeat(257))).toBe(false);
+ });
+
+ it('returns the payload untouched when the feature is off', () => {
+ const payload = payloadFor(GITHUB_SEARCH);
+ expect(markToolApprovalAllowAlways(payload, { policy: enabled({ allowAlways: false }) })).toBe(
+ payload,
+ );
+ });
+});
+
+describe('resume validation of remembered approvals', () => {
+ const policy = enabled();
+
+ it('accepts scope session only where the pause offered it', () => {
+ const offered = markToolApprovalAllowAlways(payloadFor(GITHUB_SEARCH), { policy });
+ expect(
+ resolveToolApprovalResume(offered, [
+ { tool_call_id: 'call-0', decision: 'approve', scope: 'session' },
+ ]),
+ ).toEqual({ resumeValue: { 'call-0': { type: 'approve' } } });
+
+ const notOffered = payloadFor(GITHUB_SEARCH);
+ expect(
+ resolveToolApprovalResume(notOffered, [
+ { tool_call_id: 'call-0', decision: 'approve', scope: 'session' },
+ ]),
+ ).toMatchObject({ status: 403, disallowed: ['call-0'] });
+ });
+
+ it('rejects the reserved always scope and session scope on non-approve decisions', () => {
+ const offered = markToolApprovalAllowAlways(payloadFor(GITHUB_SEARCH), { policy });
+ for (const resolution of [
+ { tool_call_id: 'call-0', decision: 'approve' as const, scope: 'always' as const },
+ { tool_call_id: 'call-0', decision: 'reject' as const, scope: 'session' as const },
+ ]) {
+ expect(resolveToolApprovalResume(offered, [resolution])).toMatchObject({ status: 403 });
+ }
+ });
+});
+
+describe('collectToolApprovalAllows', () => {
+ it('re-checks eligibility against the live policy', () => {
+ const offered = markToolApprovalAllowAlways(payloadFor(GITHUB_SEARCH), { policy: enabled() });
+ const resolutions: Agents.ToolApprovalResolution[] = [
+ { tool_call_id: 'call-0', decision: 'approve', scope: 'session' },
+ ];
+ expect(collectToolApprovalAllows(offered, resolutions, enabled())).toEqual([GITHUB_SEARCH]);
+ expect(
+ collectToolApprovalAllows(offered, resolutions, enabled({ deny: [GITHUB_SEARCH] })),
+ ).toEqual([]);
+ expect(
+ collectToolApprovalAllows(offered, resolutions, enabled({ allowAlways: false })),
+ ).toEqual([]);
+ });
+});
+
+describe('buildEffectiveToolApprovalPolicy', () => {
+ const alias = { name: GITHUB_SEARCH, aliasName: 'legacy_search_mcp_github' };
+
+ it('heals ask rules before folding remembered tools, so a healed ask still wins', async () => {
+ const policy = buildEffectiveToolApprovalPolicy(
+ enabled({ ask: ['legacy_search_mcp_github'] }),
+ [alias],
+ [GITHUB_SEARCH],
+ );
+ expect(policy?.allow ?? []).not.toContain(GITHUB_SEARCH);
+ expect(await decide(policy, GITHUB_SEARCH)).toBe('ask');
+ });
+
+ it('lets scheduled admission skip a run whose every known tool is remembered', () => {
+ const agents = [{ tools: [GITHUB_SEARCH, GITLAB_SEARCH] }];
+ expect(canAgentGraphPause({ policy: enabled(), agents })).toBe(true);
+ expect(
+ canAgentGraphPause({ policy: enabled(), agents, toolApprovalAllows: [GITHUB_SEARCH] }),
+ ).toBe(true);
+ expect(
+ canAgentGraphPause({
+ policy: enabled(),
+ agents,
+ toolApprovalAllows: [GITHUB_SEARCH, GITLAB_SEARCH],
+ }),
+ ).toBe(false);
+ expect(
+ canAgentGraphPause({
+ policy: enabled({ allowAlways: false }),
+ agents,
+ toolApprovalAllows: [GITHUB_SEARCH, GITLAB_SEARCH],
+ }),
+ ).toBe(true);
+ });
+
+ it('keeps admission paused for a remembered tool a healed ask rule matches', () => {
+ expect(
+ canAgentGraphPause({
+ policy: enabled({ ask: ['legacy_search_mcp_github'] }),
+ agents: [{ tools: [GITHUB_SEARCH], mcpToolAliases: [alias] }],
+ toolApprovalAllows: [GITHUB_SEARCH],
+ }),
+ ).toBe(true);
+ });
+});
+
+describe('recordToolApprovalAllows', () => {
+ const offered = markToolApprovalAllowAlways(payloadFor(GITHUB_SEARCH, GITLAB_SEARCH), {
+ policy: enabled(),
+ });
+ const resolutions = [
+ { tool_call_id: 'call-0', decision: 'approve', scope: 'session' },
+ { tool_call_id: 'call-1', decision: 'approve' },
+ ];
+
+ it('stores remembered tools and exposes them to the rebuilt run', async () => {
+ const addConvoToolApprovalAllows = jest.fn().mockResolvedValue(true);
+ const request = {
+ resolvedConversation: { conversationId: 'c1', toolApprovalAllows: ['other_tool'] },
+ };
+ const stored = await recordToolApprovalAllows({
+ userId: 'u1',
+ conversationId: 'c1',
+ policy: enabled(),
+ pendingAction: { payload: offered },
+ resolutions,
+ request,
+ addConvoToolApprovalAllows,
+ });
+ expect(stored).toEqual([GITHUB_SEARCH]);
+ expect(addConvoToolApprovalAllows).toHaveBeenCalledWith({
+ user: 'u1',
+ conversationId: 'c1',
+ toolNames: [GITHUB_SEARCH],
+ max: MAX_CONVERSATION_TOOL_ALLOWS,
+ });
+ expect(request.resolvedConversation.toolApprovalAllows).toEqual(['other_tool', GITHUB_SEARCH]);
+ });
+
+ it('passes the configured cap to storage and rechecks against healed rules', async () => {
+ const addConvoToolApprovalAllows = jest.fn().mockResolvedValue(true);
+ await recordToolApprovalAllows({
+ userId: 'u1',
+ conversationId: 'c1',
+ policy: enabled({ allowAlwaysMaxTools: 5 }),
+ pendingAction: { payload: offered },
+ resolutions,
+ request: {},
+ addConvoToolApprovalAllows,
+ });
+ expect(addConvoToolApprovalAllows).toHaveBeenCalledWith(expect.objectContaining({ max: 5 }));
+
+ addConvoToolApprovalAllows.mockClear();
+ const stored = await recordToolApprovalAllows({
+ userId: 'u1',
+ conversationId: 'c1',
+ policy: enabled({ ask: ['legacy_search_mcp_github'] }),
+ pendingAction: { payload: offered },
+ resolutions,
+ agents: [
+ { mcpToolAliases: [{ name: GITHUB_SEARCH, aliasName: 'legacy_search_mcp_github' }] },
+ ],
+ request: {},
+ addConvoToolApprovalAllows,
+ });
+ expect(stored).toEqual([]);
+ expect(addConvoToolApprovalAllows).not.toHaveBeenCalled();
+ });
+
+ it('rechecks against the alias pairs the paused run kept for its offers', async () => {
+ const pairs = [{ name: GITHUB_SEARCH, aliasName: 'legacy_search_mcp_github' }];
+ expect(collectAllowAlwaysAliases(offered, [...pairs, { name: 'x', aliasName: 'y' }])).toEqual(
+ pairs,
+ );
+ expect(collectAllowAlwaysAliases(payloadFor(GITHUB_SEARCH), pairs)).toBeUndefined();
+
+ const addConvoToolApprovalAllows = jest.fn().mockResolvedValue(true);
+ const stored = await recordToolApprovalAllows({
+ userId: 'u1',
+ conversationId: 'c1',
+ policy: enabled({ ask: ['legacy_search_mcp_github'] }),
+ pendingAction: { payload: offered, toolApprovalAliases: pairs },
+ resolutions,
+ agents: [{}],
+ request: {},
+ addConvoToolApprovalAllows,
+ });
+ expect(stored).toEqual([]);
+ expect(addConvoToolApprovalAllows).not.toHaveBeenCalled();
+ });
+
+ it('degrades to a one-time approval when storage fails', async () => {
+ const request = { resolvedConversation: { conversationId: 'c1' } };
+ const stored = await recordToolApprovalAllows({
+ userId: 'u1',
+ conversationId: 'c1',
+ policy: enabled(),
+ pendingAction: { payload: offered },
+ resolutions,
+ request,
+ addConvoToolApprovalAllows: jest.fn().mockRejectedValue(new Error('db down')),
+ });
+ expect(stored).toEqual([]);
+ expect(request.resolvedConversation).toEqual({ conversationId: 'c1' });
+ });
+
+ it('approves once and stores nothing when a hook registered after the pause applies', async () => {
+ const addConvoToolApprovalAllows = jest.fn().mockResolvedValue(true);
+ const pluginHookSource = {
+ hasHooks: () => true,
+ hasToolApprovalHooks: (names?: readonly string[]) => names?.includes(GITHUB_SEARCH) === true,
+ register: () => 0,
+ };
+ const request = { resolvedConversation: { conversationId: 'c1' } };
+ const viaPlugin = await recordToolApprovalAllows({
+ userId: 'u1',
+ conversationId: 'c1',
+ policy: enabled(),
+ pendingAction: { payload: offered },
+ resolutions,
+ pluginHookSource,
+ request,
+ addConvoToolApprovalAllows,
+ });
+ expect(viaPlugin).toEqual([]);
+
+ const hookContexts: unknown[] = [];
+ registerToolApprovalHook((context) => {
+ hookContexts.push(context);
+ return async () => ({ decision: 'ask' as const });
+ });
+ try {
+ const viaProgrammatic = await recordToolApprovalAllows({
+ userId: 'u1',
+ conversationId: 'c1',
+ policy: enabled(),
+ pendingAction: { payload: offered },
+ resolutions,
+ hookContext: { userId: 'u1', conversationId: 'c1', tenantId: 't1' },
+ request,
+ addConvoToolApprovalAllows,
+ });
+ expect(viaProgrammatic).toEqual([]);
+ } finally {
+ clearToolApprovalHooks();
+ }
+ expect(hookContexts).toEqual([{ userId: 'u1', conversationId: 'c1', tenantId: 't1' }]);
+ expect(addConvoToolApprovalAllows).not.toHaveBeenCalled();
+ expect(request.resolvedConversation).toEqual({ conversationId: 'c1' });
+ });
+
+ it('does nothing for ask-user-question resumes', async () => {
+ const addConvoToolApprovalAllows = jest.fn();
+ await recordToolApprovalAllows({
+ userId: 'u1',
+ conversationId: 'c1',
+ policy: enabled(),
+ pendingAction: {
+ payload: { type: 'ask_user_question', question: { question: 'q' } },
+ },
+ resolutions: undefined,
+ request: {},
+ addConvoToolApprovalAllows,
+ });
+ expect(addConvoToolApprovalAllows).not.toHaveBeenCalled();
+ });
+});
+
+describe('invariant: Always allow is offered only when the next identical call is auto-approved', () => {
+ const STRIPPED = GITHUB_SEARCH;
+ const LEGACY = 'legacy_search_mcp_github';
+ const alias = { name: STRIPPED, aliasName: LEGACY };
+ const askHook = async () => ({ decision: 'ask' as const, reason: 'per-argument check' });
+ const askPluginSource = {
+ hasHooks: () => true,
+ hasToolApprovalHooks: () => true,
+ register: ({ registry }: { registry: HookRegistry }) => {
+ registry.register('PreToolUse', { hooks: [askHook] });
+ return 1;
+ },
+ };
+
+ interface InvariantCase {
+ label: string;
+ policy: NonNullable<TToolApprovalPolicy>;
+ /** Spelling the paused call used. */
+ paused: string;
+ /** Spellings the next identical call may arrive under. */
+ next: string[];
+ stored?: string[];
+ programmaticHook?: boolean;
+ pluginHook?: boolean;
+ /** The hook is registered after the pause (restart or deploy) instead of before it. */
+ hookAfterPause?: boolean;
+ offered: boolean;
+ }
+
+ const cases: InvariantCase[] = [
+ {
+ label: 'static ask',
+ policy: enabled({ ask: [STRIPPED] }),
+ paused: STRIPPED,
+ next: [STRIPPED],
+ offered: false,
+ },
+ {
+ label: 'default mode ask',
+ policy: enabled({ mode: 'default' }),
+ paused: STRIPPED,
+ next: [STRIPPED],
+ offered: true,
+ },
+ {
+ label: 'programmatic hook ask',
+ policy: enabled(),
+ paused: STRIPPED,
+ next: [STRIPPED],
+ programmaticHook: true,
+ offered: false,
+ },
+ {
+ label: 'plugin hook ask',
+ policy: enabled(),
+ paused: STRIPPED,
+ next: [STRIPPED],
+ pluginHook: true,
+ offered: false,
+ },
+ {
+ label: 'programmatic hook registered after the pause',
+ policy: enabled(),
+ paused: STRIPPED,
+ next: [STRIPPED],
+ programmaticHook: true,
+ hookAfterPause: true,
+ offered: true,
+ },
+ {
+ label: 'plugin hook registered after the pause',
+ policy: enabled(),
+ paused: STRIPPED,
+ next: [STRIPPED],
+ pluginHook: true,
+ hookAfterPause: true,
+ offered: true,
+ },
+ {
+ label: 'admin deny',
+ policy: enabled({ deny: [STRIPPED] }),
+ paused: STRIPPED,
+ next: [STRIPPED],
+ offered: false,
+ },
+ {
+ label: 'admin ask on the alias spelling',
+ policy: enabled({ ask: [LEGACY] }),
+ paused: STRIPPED,
+ next: [STRIPPED, LEGACY],
+ offered: false,
+ },
+ {
+ label: 'admin deny on the stripped spelling, paused as legacy',
+ policy: enabled({ deny: [STRIPPED] }),
+ paused: LEGACY,
+ next: [LEGACY],
+ offered: false,
+ },
+ {
+ label: 'remembered legacy spelling',
+ policy: enabled(),
+ paused: LEGACY,
+ next: [STRIPPED, LEGACY],
+ offered: true,
+ },
+ {
+ label: 'remembered stripped spelling',
+ policy: enabled(),
+ paused: STRIPPED,
+ next: [LEGACY, STRIPPED],
+ offered: true,
+ },
+ {
+ label: 'dontAsk',
+ policy: enabled({ mode: 'dontAsk' }),
+ paused: STRIPPED,
+ next: [STRIPPED],
+ offered: false,
+ },
+ {
+ label: 'flag off',
+ policy: enabled({ allowAlways: false }),
+ paused: STRIPPED,
+ next: [STRIPPED],
+ offered: false,
+ },
+ {
+ label: 'cap reached',
+ policy: enabled({ allowAlwaysMaxTools: 1 }),
+ paused: STRIPPED,
+ next: [STRIPPED],
+ stored: ['other_tool'],
+ offered: false,
+ },
+ ];
+
+ afterEach(() => clearToolApprovalHooks());
+
+ /** Decide one call exactly as `createRun` wires it: effective policy plus registered hooks. */
+ async function runDecision(row: InvariantCase, allows: string[], toolName: string) {
+ const wiring = buildHITLRunWiring(
+ buildEffectiveToolApprovalPolicy(row.policy, [alias], allows),
+ {},
+ [alias],
+ );
+ if (wiring == null) {
+ return 'allow';
+ }
+ if (row.pluginHook) {
+ askPluginSource.register({ registry: wiring.hooks });
+ }
+ const result = await executeHooks({
+ registry: wiring.hooks,
+ matchQuery: toolName,
+ input: {
+ hook_event_name: 'PreToolUse',
+ runId: 'invariant',
+ toolName,
+ toolInput: {},
+ toolUseId: 'next-call',
+ },
+ });
+ return result.decision ?? 'allow';
+ }
+
+ it.each(cases)('$label', async (row) => {
+ const registerHooks = () => {
+ if (row.programmaticHook) {
+ registerToolApprovalHook(() => askHook);
+ }
+ return row.pluginHook ? askPluginSource : undefined;
+ };
+ const agents = [{ mcpToolAliases: [alias] }];
+ const hooksAtPause = row.hookAfterPause ? undefined : registerHooks();
+ const marked = markToolApprovalAllowAlways(payloadFor(row.paused), {
+ policy: row.policy,
+ agents,
+ storedTools: row.stored,
+ pluginHookSource: hooksAtPause,
+ });
+ const offered = marked.review_configs[0].allow_always === true;
+ expect(offered).toBe(row.offered);
+ const pluginHookSource = row.hookAfterPause ? registerHooks() : hooksAtPause;
+
+ const addConvoToolApprovalAllows = jest.fn().mockResolvedValue(true);
+ const recorded = await recordToolApprovalAllows({
+ userId: 'u1',
+ conversationId: 'c1',
+ policy: row.policy,
+ pendingAction: { payload: marked },
+ resolutions: [{ tool_call_id: 'call-0', decision: 'approve', scope: 'session' }],
+ agents,
+ pluginHookSource,
+ request: {},
+ addConvoToolApprovalAllows,
+ });
+ const remembered = offered && row.hookAfterPause !== true;
+ expect(recorded).toEqual(remembered ? [row.paused] : []);
+ const allows = resolveRunToolApprovalAllows(
+ row.policy,
+ { conversationId: 'c1', toolApprovalAllows: [...(row.stored ?? []), ...recorded] },
+ 'c1',
+ );
+ for (const spelling of row.next) {
+ const decision = await runDecision(row, allows, spelling);
+ if (remembered) {
+ expect(decision).toBe('allow');
+ } else if (row.policy.enabled === true && row.policy.mode !== 'dontAsk') {
+ expect(decision).not.toBe('allow');
+ }
+ }
+ if (remembered) {
+ expect(await runDecision(row, allows, GITLAB_SEARCH)).toBe('ask');
+ expect(
+ canAgentGraphPause({
+ policy: row.policy,
+ agents: [{ tools: row.next, mcpToolAliases: [alias] }],
+ toolApprovalAllows: allows,
+ }),
+ ).toBe(false);
+ }
+ });
+});
diff --git a/packages/api/src/agents/hitl/allow.ts b/packages/api/src/agents/hitl/allow.ts
new file mode 100644
index 0000000000..9be9145b7b
--- /dev/null
+++ b/packages/api/src/agents/hitl/allow.ts
@@ -0,0 +1,471 @@
+import { logger } from '@librechat/data-schemas';
+import type { Agents, TToolApprovalPolicy } from 'librechat-data-provider';
+import type { PluginHookSource } from '~/agents/hooks/source';
+import type { MCPToolAlias } from '~/tools/classification';
+import type { ToolApprovalHookContext } from './hooks';
+import { buildToolApprovalHooks, resolvedToolApprovalHooksCanMatch } from './hooks';
+import { healToolApprovalPolicy, isHITLEnabled } from './policy';
+import { isStatefulCodeEnvironmentToolName } from './byom';
+import { getSafeErrorMetadata } from '~/utils/errors';
+
+/** Default for `toolApproval.allowAlwaysMaxTools`: remembered tools per conversation. */
+export const MAX_CONVERSATION_TOOL_ALLOWS = 64;
+/** Default for `toolApproval.allowAlwaysMaxToolNameLength`. */
+export const MAX_ALLOWED_TOOL_NAME_LENGTH = 256;
+
+/** Configured cap on remembered tools per conversation. */
+export function getToolAllowAlwaysMaxTools(policy: TToolApprovalPolicy | undefined): number {
+ return policy?.allowAlwaysMaxTools ?? MAX_CONVERSATION_TOOL_ALLOWS;
+}
+
+/** Agent shape that carries the MCP key-spelling aliases createRun heals against. */
+export interface ToolAllowAlwaysAgent {
+ readonly mcpToolAliases?: readonly MCPToolAlias[];
+}
+
+function collectAgentAliases(
+ agents: readonly (ToolAllowAlwaysAgent | null | undefined)[] | undefined,
+): MCPToolAlias[] {
+ const aliases: MCPToolAlias[] = [];
+ for (const agent of agents ?? []) {
+ aliases.push(...(agent?.mcpToolAliases ?? []));
+ }
+ return aliases;
+}
+
+/** Anchored glob match, identical to the SDK's `createToolPolicyHook` semantics. */
+function matchesAny(patterns: readonly string[] | undefined, name: string): boolean {
+ if (patterns == null || patterns.length === 0) {
+ return false;
+ }
+ return patterns.some((pattern) => {
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
+ return new RegExp('^' + escaped.replace(/\*/g, '.*') + '$').test(name);
+ });
+}
+
+/** Whether the admin enabled remembered allows and the current mode can honor them. */
+export function isToolAllowAlwaysEnabled(
+ policy: TToolApprovalPolicy | undefined,
+): policy is NonNullable<TToolApprovalPolicy> {
+ return isHITLEnabled(policy) && policy.allowAlways === true && policy.mode !== 'dontAsk';
+}
+
+/**
+ * Whether one concrete tool name may be remembered for a conversation.
+ *
+ * The name is stored and matched literally, so it must not contain the glob wildcard.
+ * Admin `deny` and `ask` matches are ineligible (an `ask` entry is the admin's
+ * "always prompt" rule), and LibreChat's native code tools stay under the code
+ * approval picker instead.
+ */
+export function isToolAllowAlwaysEligible(
+ policy: TToolApprovalPolicy | undefined,
+ toolName: unknown,
+): toolName is string {
+ if (!isToolAllowAlwaysEnabled(policy)) {
+ return false;
+ }
+ if (
+ typeof toolName !== 'string' ||
+ toolName.length === 0 ||
+ toolName.length > (policy.allowAlwaysMaxToolNameLength ?? MAX_ALLOWED_TOOL_NAME_LENGTH) ||
+ toolName.includes('*')
+ ) {
+ return false;
+ }
+ if (isStatefulCodeEnvironmentToolName(toolName)) {
+ return false;
+ }
+ return !matchesAny(policy.deny, toolName) && !matchesAny(policy.ask, toolName);
+}
+
+/**
+ * Every spelling the runtime can present for one tool: the name itself plus the other MCP
+ * key spelling of any alias pair it belongs to. Only exact alias pairs are followed, so a
+ * different tool with a similar name is never included.
+ */
+export function getEquivalentToolNames(
+ toolName: string,
+ aliases: readonly MCPToolAlias[] = [],
+): string[] {
+ const names = new Set([toolName]);
+ for (const { name, aliasName } of aliases) {
+ if (name === toolName) {
+ names.add(aliasName);
+ } else if (aliasName === toolName) {
+ names.add(name);
+ }
+ }
+ return [...names];
+}
+
+/** Eligible only when every spelling of the tool is, so a `deny`/`ask` on either spelling wins. */
+function isToolAllowAlwaysGroupEligible(
+ policy: TToolApprovalPolicy | undefined,
+ toolName: unknown,
+ aliases: readonly MCPToolAlias[],
+): toolName is string {
+ if (!isToolAllowAlwaysEligible(policy, toolName)) {
+ return false;
+ }
+ return getEquivalentToolNames(toolName, aliases).every((name) =>
+ isToolAllowAlwaysEligible(policy, name),
+ );
+}
+
+/**
+ * Whether a programmatic or plugin `PreToolUse` hook could decide for any spelling of a tool.
+ * The interrupt payload does not record which hook asked, so a remembered `allow` cannot be
+ * shown to hold whenever such a hook can run for the tool: it folds `ask` over the stored
+ * allow and the next call pauses again. Agent-scoped hooks count regardless of agent here.
+ */
+function toolApprovalHookCanApply(
+ names: readonly string[],
+ hookContext: ToolApprovalHookContext,
+ pluginHookSource: PluginHookSource | undefined,
+): boolean {
+ const hooks = buildToolApprovalHooks(hookContext).map(({ hook, matcher }) => ({ hook, matcher }));
+ if (resolvedToolApprovalHooksCanMatch(hooks, names)) {
+ return true;
+ }
+ if (pluginHookSource == null) {
+ return false;
+ }
+ return pluginHookSource.hasToolApprovalHooks != null
+ ? pluginHookSource.hasToolApprovalHooks(names)
+ : pluginHookSource.hasHooks();
+}
+
+/**
+ * The approval policy a run actually evaluates: `deny`/`ask`/`allow` healed against the
+ * tools' other MCP key spellings, then the conversation's remembered tools folded in as
+ * exact-name allows for every spelling of each remembered tool. Every "Always allow" decision (offer, resume re-check, scheduled
+ * admission, run) reads this one shape so they cannot drift apart.
+ */
+export function buildEffectiveToolApprovalPolicy(
+ policy: TToolApprovalPolicy | undefined,
+ aliases: readonly MCPToolAlias[],
+ allowedTools?: readonly string[],
+): TToolApprovalPolicy | undefined {
+ return applyConversationToolAllows(
+ healToolApprovalPolicy(policy, aliases),
+ allowedTools,
+ aliases,
+ );
+}
+
+export interface MarkToolApprovalAllowAlwaysOptions {
+ /** Endpoint `toolApproval` policy, before healing. */
+ policy: TToolApprovalPolicy | undefined;
+ /** Reachable agents of the paused run; their MCP aliases heal `deny`/`ask`. */
+ agents?: readonly (ToolAllowAlwaysAgent | null | undefined)[];
+ /** Aliases the paused run discovered at runtime, such as from lazily resolved subagents. */
+ aliases?: readonly MCPToolAlias[];
+ /** Tools the conversation already remembers, to keep offers within the cap. */
+ storedTools?: readonly string[];
+ /** Request context the run resolves programmatic approval hooks with. */
+ hookContext?: ToolApprovalHookContext;
+ /** Deployment plugin hooks the run registers after the policy hooks. */
+ pluginHookSource?: PluginHookSource;
+}
+
+/**
+ * Mark every review config whose tool the user may approve for the rest of the
+ * conversation. The offer is made only when storing the name would auto-approve the next
+ * identical call on the run's own decision path: every spelling passes the healed static
+ * policy, no programmatic or plugin hook can apply to it, and the conversation's remembered
+ * list stays within `allowAlwaysMaxTools`.
+ */
+export function markToolApprovalAllowAlways(
+ payload: Agents.ToolApprovalInterruptPayload,
+ {
+ policy,
+ agents,
+ aliases: runAliases = [],
+ storedTools = [],
+ hookContext = {},
+ pluginHookSource,
+ }: MarkToolApprovalAllowAlwaysOptions,
+): Agents.ToolApprovalInterruptPayload {
+ if (!isToolAllowAlwaysEnabled(policy)) {
+ return payload;
+ }
+ const aliases = [...collectAgentAliases(agents), ...runAliases];
+ const effective = buildEffectiveToolApprovalPolicy(policy, aliases);
+ const maxTools = getToolAllowAlwaysMaxTools(policy);
+ /** Only the prefix the run honors counts as remembered; see `applyConversationToolAllows`. */
+ const stored = new Set(storedTools.slice(0, maxTools));
+ let room = maxTools - stored.size;
+ const nameByToolCallId = new Map(
+ payload.action_requests.map((request) => [request.tool_call_id, request.name]),
+ );
+ const offeredNames = new Set<string>();
+ let changed = false;
+ const review_configs = payload.review_configs.map((config) => {
+ const name = nameByToolCallId.get(config.tool_call_id);
+ if (
+ !config.allowed_decisions.includes('approve') ||
+ !isToolAllowAlwaysGroupEligible(effective, name, aliases) ||
+ toolApprovalHookCanApply(getEquivalentToolNames(name, aliases), hookContext, pluginHookSource)
+ ) {
+ return config;
+ }
+ if (!stored.has(name) && !offeredNames.has(name)) {
+ if (room <= 0) {
+ return config;
+ }
+ room--;
+ offeredNames.add(name);
+ }
+ changed = true;
+ return { ...config, allow_always: true };
+ });
+ return changed ? { ...payload, review_configs } : payload;
+}
+
+/**
+ * The alias pairs a pause must keep so resume can recheck its offers against the same
+ * spellings the paused run healed with: only pairs of tools marked `allow_always`, since
+ * resume stores nothing else. Undefined when nothing was offered.
+ */
+export function collectAllowAlwaysAliases(
+ payload: Agents.ToolApprovalInterruptPayload | undefined,
+ aliases: readonly MCPToolAlias[],
+): MCPToolAlias[] | undefined {
+ if (payload?.type !== 'tool_approval' || aliases.length === 0) {
+ return undefined;
+ }
+ const nameByToolCallId = new Map(
+ payload.action_requests.map((request) => [request.tool_call_id, request.name]),
+ );
+ const offered = new Set<string>();
+ for (const config of payload.review_configs) {
+ const name = nameByToolCallId.get(config.tool_call_id);
+ if (config.allow_always === true && typeof name === 'string') {
+ offered.add(name);
+ }
+ }
+ const kept = aliases
+ .filter(({ name, aliasName }) => offered.has(name) || offered.has(aliasName))
+ .map(({ name, aliasName }) => ({ name, aliasName }));
+ return kept.length > 0 ? kept : undefined;
+}
+
+/** Alias pairs persisted on a pending action, dropping any malformed entry. */
+function readPendingActionAliases(value: unknown): MCPToolAlias[] {
+ if (!Array.isArray(value)) {
+ return [];
+ }
+ return value.filter(
+ (entry): entry is MCPToolAlias =>
+ entry != null &&
+ typeof entry.name === 'string' &&
+ typeof entry.aliasName === 'string' &&
+ entry.name !== '' &&
+ entry.aliasName !== '',
+ );
+}
+
+/**
+ * Tool names the user approved with `scope: 'session'` in a validated resume batch.
+ * Eligibility is re-checked against the live policy, so a pause created before an
+ * admin tightened the config cannot store a now-ineligible name.
+ */
+export function collectToolApprovalAllows(
+ payload: Agents.ToolApprovalInterruptPayload,
+ resolutions: readonly Agents.ToolApprovalResolution[],
+ policy: TToolApprovalPolicy | undefined,
+ aliases: readonly MCPToolAlias[] = [],
+): string[] {
+ if (!isToolAllowAlwaysEnabled(policy)) {
+ return [];
+ }
+ const nameByToolCallId = new Map(
+ payload.action_requests.map((request) => [request.tool_call_id, request.name]),
+ );
+ const offered = new Set(
+ payload.review_configs
+ .filter((config) => config.allow_always === true)
+ .map((config) => config.tool_call_id),
+ );
+ const names = new Set<string>();
+ for (const resolution of resolutions) {
+ if (
+ resolution.decision !== 'approve' ||
+ resolution.scope !== 'session' ||
+ !offered.has(resolution.tool_call_id)
+ ) {
+ continue;
+ }
+ const name = nameByToolCallId.get(resolution.tool_call_id);
+ if (isToolAllowAlwaysGroupEligible(policy, name, aliases)) {
+ names.add(name);
+ }
+ }
+ return [...names];
+}
+
+/** Stored allows for the conversation the run executes, or none for any other record. */
+export function getConversationToolApprovalAllows(
+ conversation: { conversationId?: string | null; toolApprovalAllows?: unknown } | null | undefined,
+ conversationId: string | null | undefined,
+): string[] {
+ if (
+ conversation == null ||
+ typeof conversationId !== 'string' ||
+ conversationId === '' ||
+ conversation.conversationId !== conversationId ||
+ !Array.isArray(conversation.toolApprovalAllows)
+ ) {
+ return [];
+ }
+ return conversation.toolApprovalAllows.filter((name): name is string => typeof name === 'string');
+}
+
+/**
+ * Remembered tools a run may honor: none unless the endpoint policy enables the feature,
+ * and only from the stored record of the conversation the run executes.
+ */
+export function resolveRunToolApprovalAllows(
+ endpointPolicy: TToolApprovalPolicy | undefined,
+ conversation: { conversationId?: string | null; toolApprovalAllows?: unknown } | null | undefined,
+ conversationId: string | null | undefined,
+): string[] {
+ if (!isToolAllowAlwaysEnabled(endpointPolicy)) {
+ return [];
+ }
+ return getConversationToolApprovalAllows(conversation, conversationId);
+}
+
+/**
+ * Fold a conversation's remembered tools into the static policy as exact-name `allow`
+ * entries, one per spelling in `aliases` so a tool keeps its approval across its legacy and
+ * stripped MCP keys. A tool with any `deny`/`ask`-matched spelling adds nothing. The SDK checks `deny` then `ask` before `allow`, and programmatic hooks fold
+ * `deny > ask > allow` on top, so a remembered tool can never loosen an admin rule.
+ * Call this AFTER alias healing so healed `deny`/`ask` names still take precedence.
+ */
+export function applyConversationToolAllows(
+ policy: TToolApprovalPolicy | undefined,
+ allowedTools: readonly string[] | undefined,
+ aliases: readonly MCPToolAlias[] = [],
+): TToolApprovalPolicy | undefined {
+ if (!isToolAllowAlwaysEnabled(policy) || allowedTools == null || allowedTools.length === 0) {
+ return policy;
+ }
+ const additions = new Set<string>();
+ for (const name of allowedTools.slice(0, getToolAllowAlwaysMaxTools(policy))) {
+ if (isToolAllowAlwaysGroupEligible(policy, name, aliases)) {
+ getEquivalentToolNames(name, aliases).forEach((spelling) => additions.add(spelling));
+ }
+ }
+ if (additions.size === 0) {
+ return policy;
+ }
+ return { ...policy, allow: [...(policy.allow ?? []), ...additions] };
+}
+
+export interface RecordToolApprovalAllowsInput {
+ userId: string;
+ conversationId: string;
+ policy: TToolApprovalPolicy | undefined;
+ pendingAction: Pick<Agents.PendingAction, 'payload' | 'toolApprovalAliases'>;
+ resolutions: unknown;
+ /** Reachable agents of the rebuilt run; eligibility heals against their MCP aliases. */
+ agents?: readonly (ToolAllowAlwaysAgent | null | undefined)[];
+ /** Request context the rebuilt run resolves programmatic approval hooks with. */
+ hookContext?: ToolApprovalHookContext;
+ /** Deployment plugin hooks the rebuilt run registers after the policy hooks. */
+ pluginHookSource?: PluginHookSource;
+ /** Request-scoped conversation reused by the resumed run's initialization. */
+ request: {
+ resolvedConversation?: { conversationId?: string; toolApprovalAllows?: unknown } | null;
+ };
+ addConvoToolApprovalAllows: (input: {
+ user: string;
+ conversationId: string;
+ toolNames: string[];
+ max: number;
+ }) => Promise<boolean>;
+}
+
+/**
+ * Persist the tools a claimed resume approved for the rest of the conversation and
+ * expose them to the run rebuilt by the same request. Call only after every resume
+ * fence passed. A tool is stored only when the rebuilt run would auto-approve it: the
+ * live healed policy allows it and no programmatic or plugin hook can apply to it, so a
+ * hook registered after the pause turns the choice into a one-time approval. The approval itself is already claimed, so a storage failure is logged
+ * and degrades to a one-time approval: later calls prompt again, the safe direction.
+ */
+export async function recordToolApprovalAllows({
+ userId,
+ conversationId,
+ policy,
+ pendingAction,
+ resolutions,
+ agents,
+ hookContext = {},
+ pluginHookSource,
+ request,
+ addConvoToolApprovalAllows,
+}: RecordToolApprovalAllowsInput): Promise<string[]> {
+ const payload = pendingAction.payload;
+ if (payload?.type !== 'tool_approval' || !Array.isArray(resolutions)) {
+ return [];
+ }
+ /** The rebuilt agents' aliases miss pairs lazy subagents reported to the paused run. */
+ const aliases = [
+ ...collectAgentAliases(agents),
+ ...readPendingActionAliases(pendingAction.toolApprovalAliases),
+ ];
+ const eligible = collectToolApprovalAllows(
+ payload,
+ resolutions as Agents.ToolApprovalResolution[],
+ buildEffectiveToolApprovalPolicy(policy, aliases),
+ aliases,
+ );
+ const toolNames = eligible.filter(
+ (name) =>
+ !toolApprovalHookCanApply(
+ getEquivalentToolNames(name, aliases),
+ hookContext,
+ pluginHookSource,
+ ),
+ );
+ if (toolNames.length < eligible.length) {
+ logger.info(
+ '[recordToolApprovalAllows] An approval hook now applies to a remembered tool; approved once',
+ );
+ }
+ if (toolNames.length === 0) {
+ return [];
+ }
+ let stored = false;
+ try {
+ stored = await addConvoToolApprovalAllows({
+ user: userId,
+ conversationId,
+ toolNames,
+ max: getToolAllowAlwaysMaxTools(policy),
+ });
+ } catch (error) {
+ logger.warn(
+ '[recordToolApprovalAllows] Failed to store allowed tools',
+ getSafeErrorMetadata(error),
+ );
+ return [];
+ }
+ if (!stored) {
+ logger.warn('[recordToolApprovalAllows] Remembered tool limit reached; approved once');
+ return [];
+ }
+ const resolved = request.resolvedConversation;
+ if (resolved != null && resolved.conversationId === conversationId) {
+ const existing = getConversationToolApprovalAllows(resolved, conversationId);
+ request.resolvedConversation = {
+ ...resolved,
+ toolApprovalAllows: [...new Set([...existing, ...toolNames])],
+ };
+ }
+ return toolNames;
+}
diff --git a/packages/api/src/agents/hitl/index.ts b/packages/api/src/agents/hitl/index.ts
index 2467ed756b..2b53e1c1b5 100644
--- a/packages/api/src/agents/hitl/index.ts
+++ b/packages/api/src/agents/hitl/index.ts
@@ -1,4 +1,5 @@
export * from './policy';
+export * from './allow';
export * from './admission';
export * from './runtime';
export * from './resume';
diff --git a/packages/api/src/agents/hitl/policy.spec.ts b/packages/api/src/agents/hitl/policy.spec.ts
index c6f3ce69a8..dea3f646ab 100644
--- a/packages/api/src/agents/hitl/policy.spec.ts
+++ b/packages/api/src/agents/hitl/policy.spec.ts
@@ -441,6 +441,7 @@ describe('toClientPendingAction', () => {
version: 1,
targets: [{ agentId: 'agent-1', targetHash: 'a'.repeat(64) }],
},
+ toolApprovalAliases: [{ name: 'shell', aliasName: 'legacy_shell' }],
});
const clientSafe = toClientPendingAction(full);
@@ -449,6 +450,7 @@ describe('toClientPendingAction', () => {
expect(clientSafe?.requestFingerprint).toBeUndefined();
expect(clientSafe?.requestFingerprintV2).toBeUndefined();
expect(clientSafe?.codeExecutionBinding).toBeUndefined();
+ expect(clientSafe?.toolApprovalAliases).toBeUndefined();
expect(clientSafe?.projectContextKey).toBeUndefined();
expect(clientSafe?.actionId).toBe(full.actionId);
expect(clientSafe?.streamId).toBe('stream-1');
@@ -462,6 +464,7 @@ describe('toClientPendingAction', () => {
targets: [{ agentId: 'agent-1', targetHash: 'a'.repeat(64) }],
});
expect(full.projectContextKey).toBe('project:p1:r2');
+ expect(full.toolApprovalAliases).toEqual([{ name: 'shell', aliasName: 'legacy_shell' }]);
});
test('passes through nullish input', () => {
diff --git a/packages/api/src/agents/hitl/policy.ts b/packages/api/src/agents/hitl/policy.ts
index 121a97528f..dd00e19d89 100644
--- a/packages/api/src/agents/hitl/policy.ts
+++ b/packages/api/src/agents/hitl/policy.ts
@@ -393,6 +393,8 @@ export interface PendingActionContext {
resumeContext?: Record<string, unknown>;
/** Opaque server-only binding to the stateful code targets selected at pause time. */
codeExecutionBinding?: Agents.CodeExecutionApprovalBinding;
+ /** Server-only alias pairs of the offered "Always allow" tools; see `collectAllowAlwaysAliases`. */
+ toolApprovalAliases?: Agents.PendingAction['toolApprovalAliases'];
}
/** Request fields that decide which agent/graph + tool set a turn runs. */
@@ -928,12 +930,13 @@ export function buildPendingAction(
requestFingerprintV2: ctx.requestFingerprintV2,
resumeContext: ctx.resumeContext,
codeExecutionBinding: ctx.codeExecutionBinding,
+ toolApprovalAliases: ctx.toolApprovalAliases,
};
}
/**
* Client-facing projection of a pending action. `projectContextKey`, `requestFingerprint`,
- * `resumeContext`, and `codeExecutionBinding` are server-only replay state. `resumeContext`
+ * `resumeContext`, `codeExecutionBinding`, and `toolApprovalAliases` are server-only replay state. `resumeContext`
* carries resolved model parameters, so every copy that leaves the server (SSE, status,
* resume state) must go through this. The full record stays in the job store for resume.
*/
@@ -949,6 +952,7 @@ export function toClientPendingAction(
requestFingerprintV2: _requestFingerprintV2,
resumeContext: _resumeContext,
codeExecutionBinding: _codeExecutionBinding,
+ toolApprovalAliases: _toolApprovalAliases,
...clientSafe
} = pendingAction;
return clientSafe;
diff --git a/packages/api/src/agents/hitl/resume.ts b/packages/api/src/agents/hitl/resume.ts
index a16bf34882..2f87e93150 100644
--- a/packages/api/src/agents/hitl/resume.ts
+++ b/packages/api/src/agents/hitl/resume.ts
@@ -287,7 +287,8 @@ export function hasInvalidToolApprovalResolutions(
* Enforce the policy's per-tool `allowed_decisions`. Returns the `tool_call_id`s
* whose submitted decision is NOT one the interrupt's `review_configs` permits for
* that tool — so the resume route can reject a crafted request that, e.g., approves
- * a tool the policy restricted to `reject`/`respond`. A resolution for a tool with
+ * a tool the policy restricted to `reject`/`respond`, or asks to remember an approval
+ * (`scope`) the pause did not offer. A resolution for a tool with
* no matching review_config (shouldn't happen) is treated as disallowed (fail closed).
*/
export function findDisallowedDecisions(
@@ -295,11 +296,28 @@ export function findDisallowedDecisions(
resolutions: readonly Agents.ToolApprovalResolution[],
): string[] {
const allowedByToolCallId = new Map<string, Set<Agents.ToolApprovalDecisionType>>();
+ const allowAlwaysIds = new Set<string>();
for (const config of payload.review_configs) {
allowedByToolCallId.set(config.tool_call_id, new Set(config.allowed_decisions));
+ if (config.allow_always === true) {
+ allowAlwaysIds.add(config.tool_call_id);
+ }
}
return resolutions
- .filter((r) => !allowedByToolCallId.get(r.tool_call_id)?.has(r.decision))
+ .filter((r) => {
+ if (!allowedByToolCallId.get(r.tool_call_id)?.has(r.decision)) {
+ return true;
+ }
+ if (r.scope == null || r.scope === 'once') {
+ return false;
+ }
+ // A remembered approval is valid only where the pause itself offered it.
+ return !(
+ r.scope === 'session' &&
+ r.decision === 'approve' &&
+ allowAlwaysIds.has(r.tool_call_id)
+ );
+ })
.map((r) => r.tool_call_id);
}
diff --git a/packages/api/src/agents/run.ts b/packages/api/src/agents/run.ts
index 848c35019c..5c5071580c 100644
--- a/packages/api/src/agents/run.ts
+++ b/packages/api/src/agents/run.ts
@@ -96,11 +96,6 @@ import {
isSteerPreemptSupported,
isSteerTerminalContinuationSupported,
} from '~/agents/steering/runtime';
-import {
- resolveToolApprovalPolicy,
- healToolApprovalPolicy,
- exemptAskUserQuestionFromApproval,
-} from '~/agents/hitl/policy';
import {
ASK_USER_QUESTION_TOOL_NAME,
createAskUserQuestionTool,
@@ -110,6 +105,7 @@ import {
eventOnlyRunFileTools,
isRunFileSharingSupported,
} from './files/runtime';
+import { resolveToolApprovalPolicy, exemptAskUserQuestionFromApproval } from '~/agents/hitl/policy';
import { applyCustomHandoffPromptKeyCompatibility } from '~/agents/handoffPromptKeyCompatibility';
import { stripIntentFromToolRegistry, stripIntentFromToolDefinitions } from '~/agents/intent';
import { resolveConfigHeaders, resolveModelHeaders, mergeHeaders } from '~/utils/headers';
@@ -119,6 +115,7 @@ import { CREATE_FILE_TOOL_NAME, EDIT_FILE_TOOL_NAME } from '~/agents/tools';
import { buildAgentInitialToolSessions } from '~/agents/codeFilesSession';
import { getDirectDispatcher, getProxyDispatcher } from '~/utils/proxy';
import { getAzureCredentials, constructAzureURL } from '~/utils/azure';
+import { buildEffectiveToolApprovalPolicy } from '~/agents/hitl/allow';
import { prepareQueuedCodeFileContext } from '~/files/code/queued';
import { getBuiltInBaseURL } from '~/endpoints/openai/initialize';
import { getProviderConfig } from '~/endpoints/config/providers';
@@ -222,6 +219,14 @@ export function extractDiscoveredToolsFromHistory(messages: BaseMessage[]): Set<
return discoveredTools;
}
+/** MCP key-spelling aliases each run knows, including those its lazy subagents reported. */
+const runMCPToolAliases = new WeakMap<object, readonly MCPToolAlias[]>();
+
+/** The run's live alias list, so a pause can be judged against the aliases the run used. */
+export function getRunMCPToolAliases(run: object | null | undefined): readonly MCPToolAlias[] {
+ return run == null ? [] : (runMCPToolAliases.get(run) ?? []);
+}
+
export interface RunDiscoverySnapshot {
getDiscoveredTools?: () => string[];
getRunMessages?: () => BaseMessage[] | undefined;
@@ -2124,6 +2129,7 @@ export async function createRun({
eventActorCheckpointing = false,
hitlCapable = false,
resolvedToolApprovalHooks,
+ toolApprovalAllows,
toolInputValidationErrors,
sessionStartSource,
streaming = true,
@@ -2146,6 +2152,12 @@ export async function createRun({
* run. Tenant fanout can still export when tenant routing is available.
*/
centralTraceExportEnabled?: boolean;
+ /**
+ * Exact tool names the owner approved for the rest of this conversation, read from the
+ * stored conversation (never from the request body). Honored only when
+ * `toolApproval.allowAlways` is on; admin `deny`/`ask` rules and hooks still win.
+ */
+ toolApprovalAllows?: readonly string[];
/**
* Request values the deployment may export as Langfuse trace metadata
* (`langfuse.trace.conversationMetadataFields`). The conversation id,
@@ -2737,7 +2749,7 @@ export async function createRun({
);
const effectiveToolApprovalPolicy = () =>
exemptAskUserQuestionFromApproval(
- healToolApprovalPolicy(toolApprovalPolicy, mcpToolAliases),
+ buildEffectiveToolApprovalPolicy(toolApprovalPolicy, mcpToolAliases, toolApprovalAllows),
ASK_USER_QUESTION_TOOL_NAME,
);
const nativeEditFileAgentIds = collectNativeEditFileAgentIds(agents);
@@ -3035,6 +3047,7 @@ export async function createRun({
...(streamLimits && { streamLimits }),
};
const run = await Run.create(runConfig);
+ runMCPToolAliases.set(run, mcpToolAliases);
applyCustomHandoffPromptKeyCompatibility(run, runConfig.graphConfig);
applyTestRunHook(run, {
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index e7a8f156fb..4e6d0342f7 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -1094,6 +1094,23 @@ export const toolApprovalPolicySchema = z
ask: z.array(z.string()).optional(),
/** Optional reason template surfaced in the prompt; `{tool}` is interpolated. */
reason: z.string().optional(),
+ /**
+ * Offer "Always allow" on the approval card. Choosing it auto-approves that exact tool
+ * (MCP names include their server) for the rest of the conversation. The server stores
+ * and enforces the choice; `deny` and `ask` rules and programmatic hooks still win, and
+ * stored choices are ignored under `mode: 'dontAsk'` or once this is turned off.
+ * Defaults to `false`: every paused call keeps prompting. Enable it only once every
+ * replica runs a version that supports it: older replicas ignore the choice and keep
+ * prompting, so during a rolling upgrade it may not stick.
+ */
+ allowAlways: z.boolean().optional(),
+ /**
+ * Most tools one conversation may remember with "Always allow". Once reached, the card
+ * stops offering the choice for new tools. Defaults to 64.
+ */
+ allowAlwaysMaxTools: z.number().int().min(1).max(1024).optional(),
+ /** Longest tool name that may be remembered. Defaults to 256. */
+ allowAlwaysMaxToolNameLength: z.number().int().min(1).max(1024).optional(),
/**
* Programmatic policy hooks loaded from modules at startup. They layer on top of the
* static lists above for dynamic, context-aware decisions the lists can't express
diff --git a/packages/data-provider/src/types/agents.ts b/packages/data-provider/src/types/agents.ts
index 6ac03ee631..2d771b30ce 100644
--- a/packages/data-provider/src/types/agents.ts
+++ b/packages/data-provider/src/types/agents.ts
@@ -133,6 +133,8 @@ export namespace Agents {
actionId: string;
allowed_decisions: ToolApprovalDecisionType[];
description?: string;
+ /** Server-authored: an `approve` may carry `scope: 'session'` for this call. */
+ allow_always?: boolean;
};
};
@@ -473,6 +475,12 @@ export namespace Agents {
action_name: string;
tool_call_id: string;
allowed_decisions: ToolApprovalDecisionType[];
+ /**
+ * Server-authored: the user may approve this call for the rest of the conversation
+ * (`scope: 'session'`). Absent when `toolApproval.allowAlways` is off or the tool is
+ * ineligible (admin `deny`/`ask` match, native code tool, wildcard name).
+ */
+ allow_always?: boolean;
}
/** Interrupt payload for a tool-approval pause. */
@@ -591,6 +599,12 @@ export namespace Agents {
* tool execution so an approval cannot migrate to another VM or workspace.
*/
codeExecutionBinding?: CodeExecutionApprovalBinding;
+ /**
+ * Server-only MCP key-spelling pairs the paused run knew for the tools it offered
+ * "Always allow", including pairs lazily resolved subagents reported. Resume rechecks
+ * eligibility against them before remembering a tool.
+ */
+ toolApprovalAliases?: Array<{ name: string; aliasName: string }>;
}
export interface CodeExecutionApprovalTargetBinding {
@@ -606,9 +620,10 @@ export namespace Agents {
}
/**
- * Scope of a tool-approval decision — drives the "remember this" persistence
- * envelope. Storage of session/always decisions is a Slice B+ concern; the
- * field is on the wire today so route signatures don't break later.
+ * Scope of a tool-approval decision. `once` (the default) applies to this call only.
+ * `session` on an `approve` auto-approves the same tool for the rest of the
+ * conversation, and is accepted only when the call's review config sets
+ * `allow_always`. `always` is reserved and currently rejected.
*/
export type DecisionScope = 'once' | 'session' | 'always';
diff --git a/packages/data-schemas/src/methods/conversation.spec.ts b/packages/data-schemas/src/methods/conversation.spec.ts
index 5795a4231c..eaa3eadecc 100644
--- a/packages/data-schemas/src/methods/conversation.spec.ts
+++ b/packages/data-schemas/src/methods/conversation.spec.ts
@@ -8990,6 +8990,88 @@ describe('Conversation Operations', () => {
expect(result.conversations.map((c) => c.conversationId)).toEqual([convo.conversationId]);
});
});
+
+ describe('addConvoToolApprovalAllows', () => {
+ const seed = async (user = 'allow-user') => {
+ const conversationId = uuidv4();
+ await Conversation.create({ conversationId, user, title: 'Allow test', endpoint: 'agents' });
+ return conversationId;
+ };
+
+ it('stores tools owner-scoped and idempotently', async () => {
+ const conversationId = await seed();
+ const input = { conversationId, toolNames: ['search_mcp_github'], max: 64 };
+ expect(await methods.addConvoToolApprovalAllows({ ...input, user: 'intruder' })).toBe(false);
+ expect(await methods.addConvoToolApprovalAllows({ ...input, user: 'allow-user' })).toBe(true);
+ expect(await methods.addConvoToolApprovalAllows({ ...input, user: 'allow-user' })).toBe(true);
+ const stored = await Conversation.findOne({ conversationId }).lean();
+ expect(stored?.toolApprovalAllows).toEqual(['search_mcp_github']);
+ });
+
+ it('refuses a write that would exceed the bound', async () => {
+ const conversationId = await seed();
+ const user = 'allow-user';
+ expect(
+ await methods.addConvoToolApprovalAllows({
+ user,
+ conversationId,
+ toolNames: ['a', 'b'],
+ max: 2,
+ }),
+ ).toBe(true);
+ expect(
+ await methods.addConvoToolApprovalAllows({
+ user,
+ conversationId,
+ toolNames: ['c'],
+ max: 2,
+ }),
+ ).toBe(false);
+ const stored = await Conversation.findOne({ conversationId }).lean();
+ expect(stored?.toolApprovalAllows).toEqual(['a', 'b']);
+ });
+
+ it('charges only names not stored yet against the bound', async () => {
+ const conversationId = await seed();
+ const write = (toolNames: string[]) =>
+ methods.addConvoToolApprovalAllows({
+ user: 'allow-user',
+ conversationId,
+ toolNames,
+ max: 2,
+ });
+ expect(await write(['a'])).toBe(true);
+ expect(await write(['a', 'b'])).toBe(true);
+ expect(await write(['b'])).toBe(true);
+ expect(await write(['a', 'c'])).toBe(false);
+ const stored = await Conversation.findOne({ conversationId }).lean();
+ expect(stored?.toolApprovalAllows).toEqual(['a', 'b']);
+ });
+
+ it('cannot be written or cleared through generic saves or bulk imports', async () => {
+ const conversationId = await seed();
+ const user = 'allow-user';
+ await methods.addConvoToolApprovalAllows({
+ user,
+ conversationId,
+ toolNames: ['kept'],
+ max: 64,
+ });
+ await saveConvo(
+ { userId: user },
+ { conversationId, toolApprovalAllows: ['*'] },
+ { unsetFields: { toolApprovalAllows: 1 } },
+ );
+ const imported = uuidv4();
+ await methods.bulkSaveConvos([
+ { conversationId: imported, user, title: 'Imported', toolApprovalAllows: ['*'] },
+ ]);
+ const stored = await Conversation.findOne({ conversationId }).lean();
+ expect(stored?.toolApprovalAllows).toEqual(['kept']);
+ const importedDoc = await Conversation.findOne({ conversationId: imported }).lean();
+ expect(importedDoc?.toolApprovalAllows).toBeUndefined();
+ });
+ });
});
describe('stampForcedRetention', () => {
diff --git a/packages/data-schemas/src/methods/conversation.ts b/packages/data-schemas/src/methods/conversation.ts
index 2918817288..272f40a8f6 100644
--- a/packages/data-schemas/src/methods/conversation.ts
+++ b/packages/data-schemas/src/methods/conversation.ts
@@ -319,6 +319,12 @@ export interface ConversationMethods {
IConversation,
'conversationId' | 'codeEnvironmentMode' | 'codeWorkspaces' | 'codeEnvironmentRevision'
> | null>;
+ addConvoToolApprovalAllows(input: {
+ user: string;
+ conversationId: string;
+ toolNames: string[];
+ max: number;
+ }): Promise<boolean>;
readAdmittedConvoCodeEnvironmentDecision(
user: string,
conversationId: string,
@@ -2410,6 +2416,8 @@ export function createConversationMethods(
delete update.lastResponseAt;
delete update.lastResponseMessageId;
delete update.initial_agent_id;
+ /* Remembered tool approvals are granted only by a validated resume. */
+ delete update.toolApprovalAllows;
/** Ordinary saves may seed a decision, but only an explicit move may replace it. */
const decisionOnInsert = {
...(convo.codeEnvironmentMode != null && {
@@ -2431,6 +2439,7 @@ export function createConversationMethods(
delete unsetFields.lastResponseMessageId;
delete unsetFields.lastResponseAt;
delete unsetFields.initial_agent_id;
+ delete unsetFields.toolApprovalAllows;
delete unsetFields.codeEnvironmentRevision;
delete unsetFields.codeEnvironmentMode;
delete unsetFields.codeWorkspaces;
@@ -2899,6 +2908,47 @@ export function createConversationMethods(
* return the post-update decision in one round trip. A run that wins invalidates an in-flight
* transition's revision; a transition that wins is observed by this read.
*/
+ /**
+ * Remember tools the owner approved for the rest of one conversation. Owner-scoped,
+ * idempotent (`$addToSet`), and bounded: the write matches only while the stored list
+ * plus the names it does not hold yet fits `max`, so concurrent resumes cannot grow it
+ * past the cap and a name already stored costs no room. Returns whether it applied.
+ */
+ async function addConvoToolApprovalAllows({
+ user,
+ conversationId,
+ toolNames,
+ max,
+ }: {
+ user: string;
+ conversationId: string;
+ toolNames: string[];
+ max: number;
+ }): Promise<boolean> {
+ const names = [...new Set(toolNames.filter((name) => typeof name === 'string' && name))];
+ if (names.length === 0 || names.length > max) {
+ return false;
+ }
+ const Conversation = mongoose.models.Conversation as Model<IConversation>;
+ const result = await withoutMeiliIndexing(
+ Conversation.updateOne(
+ {
+ user,
+ conversationId,
+ $expr: {
+ $lte: [
+ { $size: { $setUnion: [{ $ifNull: ['$toolApprovalAllows', []] }, names] } },
+ max,
+ ],
+ },
+ },
+ { $addToSet: { toolApprovalAllows: { $each: names } } },
+ { timestamps: false },
+ ),
+ );
+ return result.matchedCount === 1;
+ }
+
async function readAdmittedConvoCodeEnvironmentDecision(user: string, conversationId: string) {
const Conversation = mongoose.models.Conversation as Model<IConversation>;
return withoutMeiliIndexing(
@@ -3044,6 +3094,7 @@ export function createConversationMethods(
delete sanitized.lastSeenAt;
delete sanitized.codeApprovalMode;
delete sanitized.initial_agent_id;
+ delete sanitized.toolApprovalAllows;
delete sanitized.codeEnvironmentRevision;
stripActorCheckpointFields(sanitized);
if (typeof sanitized.user === 'string' && typeof sanitized.chatProjectId === 'string') {
@@ -4103,6 +4154,7 @@ export function createConversationMethods(
setConvoPinned,
appendConvoMessageReference,
getConvoCodeEnvironmentDecision,
+ addConvoToolApprovalAllows,
readAdmittedConvoCodeEnvironmentDecision,
replaceConvoCodeEnvironmentDecision,
bulkSaveConvos,
diff --git a/packages/data-schemas/src/schema/convo.ts b/packages/data-schemas/src/schema/convo.ts
index abbe370389..61050a0034 100644
--- a/packages/data-schemas/src/schema/convo.ts
+++ b/packages/data-schemas/src/schema/convo.ts
@@ -42,6 +42,9 @@ const convoSchema: Schema<IConversation> = new Schema(
},
...conversationPreset,
codeEnvironmentRevision: { type: Number, select: false },
+ /** Exact tool names the owner chose to auto-approve for this conversation.
+ * Server-written only, through `addConvoToolApprovalAllows`. */
+ toolApprovalAllows: { type: [String], default: undefined },
agent_id: {
type: String,
},
diff --git a/packages/data-schemas/src/types/convo.ts b/packages/data-schemas/src/types/convo.ts
index 2232e8f187..13c7d9d1df 100644
--- a/packages/data-schemas/src/types/convo.ts
+++ b/packages/data-schemas/src/types/convo.ts
@@ -286,6 +286,8 @@ export interface IConversation extends Document {
codeEnvironmentRevision?: number;
codeEnvironmentMode?: CodeEnvironmentMode;
codeWorkspaces?: CodeWorkspaceSelection[];
+ /** Exact tool names auto-approved for this conversation; server-written only. */
+ toolApprovalAllows?: string[];
/** Immutable primary persisted-agent attribution for Insights. */
initial_agent_id?: string | null;
subagentThread?: TSubagentThreadLineage;