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: Surface Conversation Code Approval Modes (#15703)

Danny Avila4b3a6eaf0ea9
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js
index b4f9b0d017..451fb77cf5 100644
--- a/api/server/controllers/agents/client.js
+++ b/api/server/controllers/agents/client.js
@@ -55,6 +55,7 @@ const {
collectAttachedCodeEnvironmentAgentIds,
collectAttachedCodeEnvironmentPolicySettings,
buildAttachedCodeEnvironmentAdmissionHooks,
+ resolveAttachedCodeApprovalMode,
agentRunUsesCheckpointer,
canAgentGraphPause,
getPluginHookSource,
@@ -1941,6 +1942,14 @@ class AgentClient extends BaseClient {
);
}
+ const agentsEConfig = this.options.req.config?.endpoints?.[EModelEndpoint.agents];
+ const topLevelAgents = [this.options.agent, ...(this.agentConfigs?.values() ?? [])];
+ const codeApprovalMode = resolveAttachedCodeApprovalMode(
+ this.options.req.body.codeApprovalMode,
+ collectAttachedCodeEnvironmentPolicySettings(topLevelAgents),
+ agentsEConfig?.toolApproval?.enabled !== false,
+ );
+
return removeNullishValues(
Object.assign(
{
@@ -1953,6 +1962,7 @@ class AgentClient extends BaseClient {
resendFiles: this.options.resendFiles,
imageDetail: this.options.imageDetail,
maxContextTokens: this.maxContextTokens,
+ codeApprovalMode,
},
// TODO: PARSE OPTIONS BY PROVIDER, MAY CONTAIN SENSITIVE DATA
runOptions,
@@ -4303,6 +4313,11 @@ class AgentClient extends BaseClient {
collectAttachedCodeEnvironmentAgentIds(topLevelAgents);
const attachedCodeEnvironmentSettings =
collectAttachedCodeEnvironmentPolicySettings(topLevelAgents);
+ const codeApprovalMode = resolveAttachedCodeApprovalMode(
+ this.options.req.body.codeApprovalMode,
+ attachedCodeEnvironmentSettings,
+ agentsEConfig?.toolApproval?.enabled !== false,
+ );
const effectiveToolApprovalPolicy = resolveToolApprovalPolicy({
endpoint: agentsEConfig?.toolApproval,
attachedCodeEnvironment: attachedCodeEnvironmentAgentIds.size > 0,
@@ -4320,6 +4335,7 @@ class AgentClient extends BaseClient {
...buildAttachedCodeEnvironmentAdmissionHooks(
attachedCodeEnvironmentAgentIds,
attachedCodeEnvironmentSettings,
+ codeApprovalMode,
),
];
const askUserQuestionAdminDisabled = isAskUserQuestionAdminDisabled(appConfig);
@@ -4766,6 +4782,7 @@ class AgentClient extends BaseClient {
* parent slot before the text step reaches the normal handlers. */
customHandlers: reasoningLabel?.handlers(activityHandlers) ?? activityHandlers,
requestBody: config.configurable.requestBody,
+ codeApprovalMode,
user: createSafeUser(this.options.req?.user),
traceContext: buildTraceContext(this.options),
tenantId: resolveRequestTenantId(this.options.req ?? {}),
@@ -5509,6 +5526,7 @@ class AgentClient extends BaseClient {
// steer parts spliced in while the resumed segment streams.
customHandlers: reasoningLabel?.handlers(activityHandlers) ?? activityHandlers,
requestBody: config.configurable.requestBody,
+ codeApprovalMode: this.options.req.body.codeApprovalMode,
user: createSafeUser(this.options.req?.user),
traceContext: buildTraceContext(this.options),
tenantId: resolveRequestTenantId(this.options.req ?? {}),
diff --git a/api/server/controllers/agents/client.test.js b/api/server/controllers/agents/client.test.js
index c7c603e960..9cb5cf424a 100644
--- a/api/server/controllers/agents/client.test.js
+++ b/api/server/controllers/agents/client.test.js
@@ -34,6 +34,34 @@ const BaseClient = require('~/app/clients/BaseClient');
const AgentClient = require('./client');
const { resolveConfigServers } = require('~/server/services/MCP');
+describe('AgentClient code approval persistence', () => {
+ it('persists a validated mode in agent conversation options', () => {
+ const client = Object.create(AgentClient.prototype);
+ client.agentConfigs = new Map();
+ client.options = {
+ endpoint: EModelEndpoint.agents,
+ agent: {
+ id: 'attached-agent',
+ codeExecutionContext: {
+ environmentType: 'attached',
+ codeEnvironmentConfigSchema: {
+ permissions: {
+ fileWrite: { allowed: ['ask', 'allow'], default: 'ask' },
+ commandExecution: { allowed: ['ask'], default: 'ask' },
+ },
+ },
+ },
+ },
+ req: {
+ body: { codeApprovalMode: 'acceptEdits' },
+ config: { endpoints: { [EModelEndpoint.agents]: {} } },
+ },
+ };
+
+ expect(client.getSaveOptions()).toMatchObject({ codeApprovalMode: 'acceptEdits' });
+ });
+});
+
function deferred() {
let resolve;
const promise = new Promise((resolvePromise) => {
diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx
index 971179c66b..d350f5c80e 100644
--- a/client/src/components/Chat/Input/ChatForm.tsx
+++ b/client/src/components/Chat/Input/ChatForm.tsx
@@ -4,6 +4,7 @@ import { useRecoilState, useRecoilValue, useRecoilCallback } from 'recoil';
import { Constants, isAssistantsEndpoint, isAgentsEndpoint } from 'librechat-data-provider';
import { composerSurfaceClasses, composerSurfaceShadow, TextareaAutosize } from '@librechat/client';
import type { TChatProject, TMessage, TConversation } from 'librechat-data-provider';
+import type { SetterOrUpdater } from 'recoil';
import type { ExtendedFile, FileSetter, ConvoGenerator } from '~/common';
import type { QueuedMessageContext } from '~/hooks/Chat/useSteering';
import {
@@ -45,6 +46,7 @@ import PendingSteerChips from './PendingSteerChips';
import PendingQuoteChips from './PendingQuoteChips';
import AttachFileChat from './Files/AttachFileChat';
import useSteering from '~/hooks/Chat/useSteering';
+import CodeApprovalMenu from './CodeApprovalMenu';
import FileFormChat from './Files/FileFormChat';
import InFlightSteers from './InFlightSteers';
import TextareaHeader from './TextareaHeader';
@@ -70,6 +72,7 @@ interface ChatFormProps {
files: Map<string, ExtendedFile>;
setFiles: FileSetter;
conversation: TConversation | null;
+ setConversation: SetterOrUpdater<TConversation | null>;
isSubmitting: boolean;
setFilesLoading: React.Dispatch<React.SetStateAction<boolean>>;
newConversation: ConvoGenerator;
@@ -101,6 +104,7 @@ const ChatForm = memo(function ChatForm({
files,
setFiles,
conversation,
+ setConversation,
isSubmitting,
setFilesLoading,
newConversation,
@@ -779,6 +783,12 @@ const ChatForm = memo(function ChatForm({
Array.isArray(conversation?.messages) && conversation.messages.length >= 1
}
/>
+ <CodeApprovalMenu
+ conversation={conversation}
+ addedConversation={addedConvo}
+ setConversation={setConversation}
+ disabled={disableInputs || isSubmitting}
+ />
<div className="mx-auto flex" />
<TokenUsage index={index} conversation={conversation} isSubmitting={isSubmitting} />
{SpeechToText && (
@@ -850,6 +860,7 @@ function ChatFormWrapper({
files,
setFiles,
conversation,
+ setConversation,
isSubmitting,
setFilesLoading,
newConversation,
@@ -875,6 +886,7 @@ function ChatFormWrapper({
conversation?.useResponsesApi,
conversation?.model,
conversation?.maxContextTokens,
+ conversation?.codeApprovalMode,
hasMessages,
],
);
@@ -909,6 +921,7 @@ function ChatFormWrapper({
files={files}
setFiles={setFiles}
conversation={stableConversation}
+ setConversation={setConversation}
isSubmitting={isSubmitting}
setFilesLoading={setFilesLoading}
newConversation={stableNewConversation}
diff --git a/client/src/components/Chat/Input/CodeApprovalMenu.tsx b/client/src/components/Chat/Input/CodeApprovalMenu.tsx
new file mode 100644
index 0000000000..b82582ddf0
--- /dev/null
+++ b/client/src/components/Chat/Input/CodeApprovalMenu.tsx
@@ -0,0 +1,84 @@
+import { ShieldCheck, Hand } from 'lucide-react';
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+} from '@librechat/client';
+import type { CodeApprovalMode, TConversation } from 'librechat-data-provider';
+import type { SetterOrUpdater } from 'recoil';
+import { useCodeApprovalMode, useLocalize } from '~/hooks';
+
+export default function CodeApprovalMenu({
+ conversation,
+ addedConversation,
+ setConversation,
+ disabled,
+}: {
+ conversation: TConversation | null;
+ addedConversation?: TConversation | null;
+ setConversation: SetterOrUpdater<TConversation | null>;
+ disabled: boolean;
+}) {
+ const localize = useLocalize();
+ const { available, modes, selected } = useCodeApprovalMode(conversation, addedConversation);
+
+ if (!available || selected == null) {
+ return null;
+ }
+ const labels: Record<CodeApprovalMode, string> = {
+ ask: localize('com_ui_code_approval_ask'),
+ acceptEdits: localize('com_ui_code_approval_accept_edits'),
+ };
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ disabled={disabled}
+ aria-label={localize('com_ui_code_approval_mode')}
+ className="h-8 gap-1.5 rounded-full px-2 text-text-secondary"
+ data-testid="code-approval-mode"
+ >
+ {selected === 'ask' ? <Hand aria-hidden="true" /> : <ShieldCheck aria-hidden="true" />}
+ <span>{labels[selected]}</span>
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" side="top" className="w-72">
+ <DropdownMenuLabel>{localize('com_ui_code_approval_mode')}</DropdownMenuLabel>
+ <DropdownMenuRadioGroup
+ value={selected}
+ onValueChange={(value) => {
+ if (!modes.includes(value as CodeApprovalMode)) return;
+ setConversation((current) =>
+ current == null
+ ? current
+ : { ...current, codeApprovalMode: value as CodeApprovalMode },
+ );
+ }}
+ >
+ {modes.map((mode) => (
+ <DropdownMenuRadioItem key={mode} value={mode}>
+ <div>
+ <div>{labels[mode]}</div>
+ <div className="text-xs text-text-tertiary">
+ {localize(
+ mode === 'ask'
+ ? 'com_ui_code_approval_ask_description'
+ : 'com_ui_code_approval_accept_edits_description',
+ )}
+ </div>
+ </div>
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/client/src/components/Chat/Input/__tests__/CodeApprovalMenu.spec.tsx b/client/src/components/Chat/Input/__tests__/CodeApprovalMenu.spec.tsx
new file mode 100644
index 0000000000..ac393ad58e
--- /dev/null
+++ b/client/src/components/Chat/Input/__tests__/CodeApprovalMenu.spec.tsx
@@ -0,0 +1,59 @@
+import userEvent from '@testing-library/user-event';
+import { render, screen } from '@testing-library/react';
+import type { TConversation } from 'librechat-data-provider';
+import CodeApprovalMenu from '../CodeApprovalMenu';
+
+const mockSetConversation = jest.fn();
+const mockUseCodeApprovalMode = jest.fn();
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+ useCodeApprovalMode: () => mockUseCodeApprovalMode(),
+}));
+
+const conversation = {
+ conversationId: 'conversation-1',
+ endpoint: 'agents',
+ agent_id: 'agent-1',
+ title: 'Code',
+} as TConversation;
+
+describe('CodeApprovalMenu', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockUseCodeApprovalMode.mockReturnValue({
+ available: true,
+ modes: ['ask', 'acceptEdits'],
+ selected: 'ask',
+ });
+ });
+
+ test('defaults to ask and stores accept-edits on the conversation', async () => {
+ render(
+ <CodeApprovalMenu
+ conversation={conversation}
+ setConversation={mockSetConversation}
+ disabled={false}
+ />,
+ );
+
+ await userEvent.click(screen.getByTestId('code-approval-mode'));
+ await userEvent.click(await screen.findByText('com_ui_code_approval_accept_edits'));
+
+ const update = mockSetConversation.mock.calls[0][0];
+ expect(update(conversation)).toEqual({ ...conversation, codeApprovalMode: 'acceptEdits' });
+ });
+
+ test('hides the control when code approvals are unavailable', () => {
+ mockUseCodeApprovalMode.mockReturnValue({ available: false, modes: [] });
+
+ render(
+ <CodeApprovalMenu
+ conversation={conversation}
+ setConversation={mockSetConversation}
+ disabled={false}
+ />,
+ );
+ expect(screen.queryByTestId('code-approval-mode')).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/hooks/Agents/__tests__/useAgentToolPermissions.test.ts b/client/src/hooks/Agents/__tests__/useAgentToolPermissions.test.ts
index 620ebc7469..615eba9495 100644
--- a/client/src/hooks/Agents/__tests__/useAgentToolPermissions.test.ts
+++ b/client/src/hooks/Agents/__tests__/useAgentToolPermissions.test.ts
@@ -124,6 +124,31 @@ describe('useAgentToolPermissions', () => {
expect(result.current.tools).toEqual([Tools.execute_code, Tools.file_search]);
});
+ it('should use the hydrated code environment when available', () => {
+ const agentId = 'agent_test';
+ mockUseAgentsMapContext.mockReturnValue({
+ [agentId]: {
+ id: agentId,
+ tools: [Tools.execute_code],
+ code_environment_id: 'stale',
+ stateful_code_sessions: false,
+ },
+ });
+ mockUseGetAgentByIdQuery.mockReturnValue({
+ data: {
+ id: agentId,
+ tools: [Tools.execute_code],
+ code_environment_id: 'attached-vm',
+ stateful_code_sessions: true,
+ },
+ });
+
+ const { result } = renderHook(() => useAgentToolPermissions(agentId));
+
+ expect(result.current.codeEnvironmentId).toBe('attached-vm');
+ expect(result.current.statefulCodeSessionsAllowedByAgent).toBe(true);
+ });
+
it('should fallback to agent map data when API data is not available', () => {
const agentId = 'agent_test';
const agentMapData = {
diff --git a/client/src/hooks/Agents/__tests__/useCodeApprovalMode.test.ts b/client/src/hooks/Agents/__tests__/useCodeApprovalMode.test.ts
new file mode 100644
index 0000000000..8f9023c2d5
--- /dev/null
+++ b/client/src/hooks/Agents/__tests__/useCodeApprovalMode.test.ts
@@ -0,0 +1,278 @@
+import { renderHook } from '@testing-library/react';
+import type { TConversation } from 'librechat-data-provider';
+import useCodeApprovalMode from '../useCodeApprovalMode';
+
+const mockUseGetAgentsConfig = jest.fn();
+const mockUseAgentToolPermissions = jest.fn();
+const mockUseAgentsMapContext = jest.fn();
+
+jest.mock('../useGetAgentsConfig', () => () => mockUseGetAgentsConfig());
+jest.mock(
+ '../useAgentToolPermissions',
+ () => (agentId?: string) => mockUseAgentToolPermissions(agentId),
+);
+jest.mock('~/Providers', () => ({ useAgentsMapContext: () => mockUseAgentsMapContext() }));
+
+const conversation = {
+ conversationId: 'conversation-1',
+ endpoint: 'agents',
+ agent_id: 'agent-1',
+ title: 'Code',
+ createdAt: '2026-09-01T00:00:00.000Z',
+ updatedAt: '2026-09-01T00:00:00.000Z',
+ codeApprovalMode: 'acceptEdits',
+} as TConversation;
+
+describe('useCodeApprovalMode', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockUseAgentsMapContext.mockReturnValue({});
+ mockUseAgentToolPermissions.mockReturnValue({
+ agent: {
+ id: 'agent-1',
+ tools: ['execute_code'],
+ stateful_code_sessions: true,
+ code_environment_id: 'mac',
+ },
+ });
+ mockUseGetAgentsConfig.mockReturnValue({
+ agentsConfig: {
+ statefulCodeSessions: {
+ approvalsEnabled: true,
+ approvalModes: ['ask', 'acceptEdits'],
+ environments: [
+ {
+ id: 'mac',
+ name: 'Mac',
+ type: 'attached',
+ configSchema: {
+ permissions: {
+ fileWrite: { allowed: ['ask', 'allow'], default: 'ask' },
+ commandExecution: { allowed: ['ask'], default: 'ask' },
+ },
+ },
+ },
+ ],
+ },
+ },
+ });
+ });
+
+ test('returns the selected mode when the attached environment permits it', () => {
+ const { result } = renderHook(() => useCodeApprovalMode(conversation));
+
+ expect(result.current).toEqual({
+ available: true,
+ modes: ['ask', 'acceptEdits'],
+ selected: 'acceptEdits',
+ });
+ });
+
+ test('falls back to ask when a saved mode is no longer permitted', () => {
+ mockUseGetAgentsConfig.mockReturnValue({
+ agentsConfig: {
+ statefulCodeSessions: {
+ approvalsEnabled: true,
+ approvalModes: ['ask', 'acceptEdits'],
+ environments: [
+ {
+ id: 'mac',
+ name: 'Mac',
+ type: 'attached',
+ configSchema: {
+ permissions: { fileWrite: { allowed: ['ask'], default: 'ask' } },
+ },
+ },
+ ],
+ },
+ },
+ });
+
+ const { result } = renderHook(() => useCodeApprovalMode(conversation));
+
+ expect(result.current.selected).toBe('ask');
+ expect(result.current.modes).toEqual(['ask']);
+ });
+
+ test('omits the mode when approvals are administratively disabled', () => {
+ mockUseGetAgentsConfig.mockReturnValue({
+ agentsConfig: {
+ statefulCodeSessions: {
+ approvalsEnabled: false,
+ approvalModes: [],
+ environments: [{ id: 'mac', name: 'Mac', type: 'attached' }],
+ },
+ },
+ });
+
+ const { result } = renderHook(() => useCodeApprovalMode(conversation));
+
+ expect(result.current).toEqual({ available: false, modes: [], selected: undefined });
+ });
+
+ test('requires an affirmative server approval capability', () => {
+ mockUseGetAgentsConfig.mockReturnValue({
+ agentsConfig: {
+ statefulCodeSessions: {
+ environments: [{ id: 'mac', name: 'Mac', type: 'attached' }],
+ },
+ },
+ });
+
+ const { result } = renderHook(() => useCodeApprovalMode(conversation));
+
+ expect(result.current).toEqual({ available: false, modes: [], selected: undefined });
+ });
+
+ test('keeps ask fail-closed when an older server does not advertise approval modes', () => {
+ mockUseGetAgentsConfig.mockReturnValue({
+ agentsConfig: {
+ statefulCodeSessions: {
+ approvalsEnabled: true,
+ environments: [{ id: 'mac', name: 'Mac', type: 'attached' }],
+ },
+ },
+ });
+
+ const { result } = renderHook(() => useCodeApprovalMode(conversation));
+
+ expect(result.current).toEqual({ available: false, modes: [], selected: 'ask' });
+ });
+
+ test('keeps ask fail-closed while agent metadata is unavailable', () => {
+ mockUseAgentToolPermissions.mockReturnValue({ agent: undefined });
+
+ const { result } = renderHook(() => useCodeApprovalMode(conversation));
+
+ expect(result.current).toEqual({ available: false, modes: [], selected: 'ask' });
+ });
+
+ test('includes attached subagents while preserving their mandatory asks', () => {
+ const primary = {
+ id: 'agent-1',
+ tools: [],
+ stateful_code_sessions: false,
+ subagents: { enabled: true, agent_ids: ['child-1', 'child-2'] },
+ };
+ mockUseAgentToolPermissions.mockReturnValue({ agent: primary });
+ mockUseAgentsMapContext.mockReturnValue({
+ 'child-1': {
+ id: 'child-1',
+ tools: ['execute_code'],
+ stateful_code_sessions: true,
+ code_environment_id: 'mac',
+ },
+ 'child-2': {
+ id: 'child-2',
+ tools: ['execute_code'],
+ stateful_code_sessions: true,
+ code_environment_id: 'restricted',
+ },
+ });
+ mockUseGetAgentsConfig.mockReturnValue({
+ agentsConfig: {
+ statefulCodeSessions: {
+ approvalsEnabled: true,
+ approvalModes: ['ask', 'acceptEdits'],
+ environments: [
+ {
+ id: 'mac',
+ name: 'Mac',
+ type: 'attached',
+ configSchema: {
+ permissions: { fileWrite: { allowed: ['ask', 'allow'], default: 'ask' } },
+ },
+ },
+ {
+ id: 'restricted',
+ name: 'Restricted',
+ type: 'attached',
+ configSchema: {
+ permissions: { fileWrite: { allowed: ['ask'], default: 'ask' } },
+ },
+ },
+ ],
+ },
+ },
+ });
+
+ const { result } = renderHook(() => useCodeApprovalMode(conversation));
+
+ expect(result.current.available).toBe(true);
+ expect(result.current.modes).toEqual(['ask', 'acceptEdits']);
+ });
+
+ test('includes the active parallel conversation agent', () => {
+ const primary = {
+ id: 'agent-1',
+ tools: [],
+ stateful_code_sessions: false,
+ };
+ const addedAgent = {
+ id: 'agent-2',
+ tools: ['execute_code'],
+ stateful_code_sessions: true,
+ code_environment_id: 'mac',
+ };
+ mockUseAgentToolPermissions.mockImplementation((agentId?: string) => ({
+ agent: agentId === 'agent-2' ? addedAgent : primary,
+ }));
+ const addedConversation = { endpoint: 'agents', agent_id: 'agent-2' } as TConversation;
+
+ const { result } = renderHook(() => useCodeApprovalMode(conversation, addedConversation));
+
+ expect(result.current.available).toBe(true);
+ expect(result.current.modes).toEqual(['ask', 'acceptEdits']);
+ });
+
+ test('does not traverse disabled subagent configurations', () => {
+ mockUseAgentToolPermissions.mockReturnValue({
+ agent: {
+ id: 'agent-1',
+ tools: ['execute_code'],
+ stateful_code_sessions: true,
+ code_environment_id: 'restricted',
+ subagents: { enabled: false, agent_ids: ['child-1'] },
+ },
+ });
+ mockUseAgentsMapContext.mockReturnValue({
+ 'child-1': {
+ id: 'child-1',
+ tools: ['execute_code'],
+ stateful_code_sessions: true,
+ code_environment_id: 'mac',
+ },
+ });
+ mockUseGetAgentsConfig.mockReturnValue({
+ agentsConfig: {
+ statefulCodeSessions: {
+ approvalsEnabled: true,
+ approvalModes: ['ask', 'acceptEdits'],
+ environments: [
+ {
+ id: 'mac',
+ name: 'Mac',
+ type: 'attached',
+ configSchema: {
+ permissions: { fileWrite: { allowed: ['ask', 'allow'], default: 'ask' } },
+ },
+ },
+ {
+ id: 'restricted',
+ name: 'Restricted',
+ type: 'attached',
+ configSchema: {
+ permissions: { fileWrite: { allowed: ['ask'], default: 'ask' } },
+ },
+ },
+ ],
+ },
+ },
+ });
+
+ const { result } = renderHook(() => useCodeApprovalMode(conversation));
+
+ expect(result.current.modes).toEqual(['ask']);
+ expect(result.current.selected).toBe('ask');
+ });
+});
diff --git a/client/src/hooks/Agents/index.ts b/client/src/hooks/Agents/index.ts
index a553da24a0..0d32e8bfd3 100644
--- a/client/src/hooks/Agents/index.ts
+++ b/client/src/hooks/Agents/index.ts
@@ -7,5 +7,6 @@ export { default as useGetAgentsConfig } from './useGetAgentsConfig';
export { default as useAgentDefaultPermissionLevel } from './useAgentDefaultPermissionLevel';
export { default as useAgentFileConfig } from './useAgentFileConfig';
export { default as useAgentToolPermissions } from './useAgentToolPermissions';
+export { default as useCodeApprovalMode } from './useCodeApprovalMode';
export { default as useMCPToolOptions } from './useMCPToolOptions';
export * from './useApplyModelSpecAgents';
diff --git a/client/src/hooks/Agents/useAgentToolPermissions.ts b/client/src/hooks/Agents/useAgentToolPermissions.ts
index cff9e9635b..05db7cf22c 100644
--- a/client/src/hooks/Agents/useAgentToolPermissions.ts
+++ b/client/src/hooks/Agents/useAgentToolPermissions.ts
@@ -1,6 +1,6 @@
import { useMemo } from 'react';
import { Tools, EToolResources } from 'librechat-data-provider';
-import type { TEphemeralAgent } from 'librechat-data-provider';
+import type { Agent, TEphemeralAgent } from 'librechat-data-provider';
import { useGetAgentByIdQuery } from '~/data-provider';
import { useAgentsMapContext } from '~/Providers';
import { isEphemeralAgent } from '~/common';
@@ -8,8 +8,11 @@ import { isEphemeralAgent } from '~/common';
interface AgentToolPermissionsResult {
fileSearchAllowedByAgent: boolean;
codeAllowedByAgent: boolean;
+ statefulCodeSessionsAllowedByAgent: boolean;
tools: string[] | undefined;
provider?: string;
+ codeEnvironmentId?: string | null;
+ agent?: Agent;
}
/**
@@ -42,6 +45,16 @@ export default function useAgentToolPermissions(
[agentData?.provider, selectedAgent?.provider],
);
+ const codeEnvironmentId = useMemo(
+ () => agentData?.code_environment_id ?? selectedAgent?.code_environment_id,
+ [agentData?.code_environment_id, selectedAgent?.code_environment_id],
+ );
+
+ const statefulCodeSessionsAllowedByAgent = useMemo(
+ () => agentData?.stateful_code_sessions ?? selectedAgent?.stateful_code_sessions ?? false,
+ [agentData?.stateful_code_sessions, selectedAgent?.stateful_code_sessions],
+ );
+
const fileSearchAllowedByAgent = useMemo(() => {
// Check ephemeral agent settings
if (isEphemeralAgent(agentId)) {
@@ -67,6 +80,9 @@ export default function useAgentToolPermissions(
return {
fileSearchAllowedByAgent,
codeAllowedByAgent,
+ statefulCodeSessionsAllowedByAgent,
+ codeEnvironmentId,
+ agent: agentData ?? selectedAgent,
provider,
tools,
};
diff --git a/client/src/hooks/Agents/useCodeApprovalMode.ts b/client/src/hooks/Agents/useCodeApprovalMode.ts
new file mode 100644
index 0000000000..6a7b262220
--- /dev/null
+++ b/client/src/hooks/Agents/useCodeApprovalMode.ts
@@ -0,0 +1,113 @@
+import { useMemo } from 'react';
+import {
+ EModelEndpoint,
+ Tools,
+ getAllowedCodeApprovalModes,
+ CODE_APPROVAL_MODES,
+} from 'librechat-data-provider';
+import type { Agent, TAgentsMap, TConfig, TPublicCodeEnvironment } from 'librechat-data-provider';
+import type { CodeApprovalMode, TConversation } from 'librechat-data-provider';
+import useAgentToolPermissions from './useAgentToolPermissions';
+import useGetAgentsConfig from './useGetAgentsConfig';
+import { useAgentsMapContext } from '~/Providers';
+
+export default function useCodeApprovalMode(
+ conversation: TConversation | null,
+ addedConversation?: TConversation | null,
+): {
+ available: boolean;
+ modes: CodeApprovalMode[];
+ selected?: CodeApprovalMode;
+} {
+ const { agentsConfig } = useGetAgentsConfig();
+ const agentsMap = useAgentsMapContext();
+ const { agent: primaryAgent } = useAgentToolPermissions(conversation?.agent_id);
+ const { agent: addedAgent } = useAgentToolPermissions(addedConversation?.agent_id);
+ const statefulCodeSessions = agentsConfig?.statefulCodeSessions as
+ | TConfig['statefulCodeSessions']
+ | undefined;
+ const environments = statefulCodeSessions?.environments;
+ const attachedEnvironments = useMemo(
+ () =>
+ collectReachableAgents([primaryAgent, addedAgent], agentsMap)
+ .filter(
+ (agent) =>
+ agent.stateful_code_sessions === true && agent.tools?.includes(Tools.execute_code),
+ )
+ .map((agent) => findExecutionEnvironment(agent, environments))
+ .filter(
+ (environment): environment is TPublicCodeEnvironment => environment?.type === 'attached',
+ ),
+ [addedAgent, agentsMap, environments, primaryAgent],
+ );
+ const supported =
+ (conversation?.endpointType ?? conversation?.endpoint) === EModelEndpoint.agents &&
+ statefulCodeSessions?.approvalsEnabled === true;
+ const endpointModes = statefulCodeSessions?.approvalModes;
+ const available =
+ supported && endpointModes?.includes('ask') === true && attachedEnvironments.length > 0;
+ const modes = useMemo(() => {
+ if (!available) return [];
+ const allowed = new Set<CodeApprovalMode>(endpointModes?.includes('ask') ? ['ask'] : []);
+ for (const environment of attachedEnvironments) {
+ const environmentModes = getAllowedCodeApprovalModes({
+ environment: 'attached',
+ allowedModes: CODE_APPROVAL_MODES,
+ configSchema: environment.configSchema,
+ settings: environment.settings,
+ });
+ if (endpointModes?.includes('acceptEdits') && environmentModes.includes('acceptEdits')) {
+ allowed.add('acceptEdits');
+ }
+ }
+ return CODE_APPROVAL_MODES.filter((mode) => allowed.has(mode));
+ }, [attachedEnvironments, available, endpointModes]);
+ const requested = conversation?.codeApprovalMode ?? 'ask';
+ /**
+ * Fail closed while agent/environment metadata is incomplete. An affirmative
+ * server capability means `ask` is safe to submit even before an attached
+ * environment is discoverable; the server ignores it when no BYOM tool is
+ * active. Never preserve `acceptEdits` until current policy authorizes it.
+ */
+ let selected: CodeApprovalMode | undefined;
+ if (supported) {
+ selected = available && modes.includes(requested) ? requested : 'ask';
+ }
+
+ return { available, modes, selected };
+}
+
+function findExecutionEnvironment(
+ agent: Agent,
+ environments?: TPublicCodeEnvironment[],
+): TPublicCodeEnvironment | undefined {
+ return agent.code_environment_id
+ ? environments?.find((candidate) => candidate.id === agent.code_environment_id)
+ : environments?.find((candidate) => candidate.default === true);
+}
+
+function collectReachableAgents(roots: Array<Agent | undefined>, agentsMap?: TAgentsMap): Agent[] {
+ const pending = roots.filter((agent): agent is Agent => agent != null);
+ const visited = new Set<string>();
+ const agents: Agent[] = [];
+ while (pending.length > 0) {
+ const agent = pending.pop();
+ if (agent == null || visited.has(agent.id)) continue;
+ visited.add(agent.id);
+ agents.push(agent);
+ if (agent.subagents?.enabled !== true) continue;
+ const edgeIds = agent.edges?.flatMap((edge) => (Array.isArray(edge.to) ? edge.to : [edge.to]));
+ const graphIds = agent.subagents.graphs?.flatMap((graph) => graph.agent_ids);
+ const ids = [
+ ...(agent.agent_ids ?? []),
+ ...(agent.subagents?.agent_ids ?? []),
+ ...(edgeIds ?? []),
+ ...(graphIds ?? []),
+ ];
+ for (const id of ids) {
+ const candidate = agentsMap?.[id];
+ if (candidate != null) pending.push(candidate);
+ }
+ }
+ return agents;
+}
diff --git a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
index e964bb56e9..33173ab46f 100644
--- a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
@@ -13,6 +13,7 @@ const mockGetSender = jest.fn(() => 'Assistant');
const mockGetExpiry = jest.fn(() => 'expiry-key');
const mockGetQueryData = jest.fn(() => ({}));
const mockLoggerWarn = jest.fn();
+const mockGetLatestConversation = jest.fn(() => null as TConversation | null);
jest.mock('react-router-dom', () => ({
useNavigate: () => mockNavigate,
@@ -40,6 +41,11 @@ jest.mock('recoil', () => ({
}));
jest.mock('~/hooks/Files/useSetFilesToDelete', () => () => mockSetFilesToDelete);
+jest.mock('~/hooks/Agents/useCodeApprovalMode', () => () => ({
+ modes: ['ask', 'acceptEdits'],
+ selected: 'ask',
+}));
+jest.mock('~/hooks/Conversations/useGetConversation', () => () => mockGetLatestConversation);
jest.mock('~/hooks/Conversations/useGetSender', () => () => mockGetSender);
jest.mock('~/hooks/Input/useUserKey', () => () => ({ getExpiry: mockGetExpiry }));
jest.mock('~/hooks', () => ({
@@ -55,6 +61,7 @@ jest.mock('~/store', () => ({
pendingManualSkillsByConvoId: () => 'pendingManualSkills',
pendingQuotesByConvoId: () => 'pendingQuotes',
messagesSiblingIdxFamily: () => 'messagesSiblingIdx',
+ conversationByKeySelector: () => 'conversation',
},
useGetEphemeralAgent: () => mockGetEphemeralAgent,
}));
@@ -128,6 +135,22 @@ describe('useChatFunctions ask', () => {
beforeEach(() => {
jest.clearAllMocks();
mockGetQueryData.mockReturnValue({});
+ mockGetLatestConversation.mockReturnValue(null);
+ });
+
+ it('reads an approval-mode selection made immediately before send', () => {
+ mockGetLatestConversation.mockReturnValue({
+ ...conversation('conversation-1'),
+ codeApprovalMode: 'acceptEdits',
+ });
+ const { result, setSubmission } = renderAsk([]);
+
+ act(() => {
+ result.current.ask({ text: 'Edit the file', conversationId: 'conversation-1' });
+ });
+
+ const submission = setSubmission.mock.calls.at(-1)?.[0] as TSubmission;
+ expect(submission.codeApprovalMode).toBe('acceptEdits');
});
it('refuses to send to an existing conversation before its history loads', () => {
@@ -276,6 +299,7 @@ describe('useChatFunctions regenerate', () => {
});
const submission = setSubmission.mock.calls.at(-1)?.[0] as TSubmission;
+ expect(submission.codeApprovalMode).toBe('ask');
expect(submission.userMessage.overrideParentMessageId).toBe('user-1');
expect(submission.userMessage.responseMessageId).toBe('assistant-1_');
expect(submission.initialResponse?.messageId).toBe('assistant-1_');
diff --git a/client/src/hooks/Chat/useChatFunctions.ts b/client/src/hooks/Chat/useChatFunctions.ts
index 984c06f3c3..27ef3c218a 100644
--- a/client/src/hooks/Chat/useChatFunctions.ts
+++ b/client/src/hooks/Chat/useChatFunctions.ts
@@ -37,6 +37,8 @@ import {
stripStreamedIndexStamps,
} from '~/utils';
import useFocusRegeneratedResponse from '~/hooks/Chat/useFocusRegeneratedResponse';
+import useGetConversation from '~/hooks/Conversations/useGetConversation';
+import useCodeApprovalMode from '~/hooks/Agents/useCodeApprovalMode';
import useSetFilesToDelete from '~/hooks/Files/useSetFilesToDelete';
import useGetSender from '~/hooks/Conversations/useGetSender';
import store, { useGetEphemeralAgent } from '~/store';
@@ -224,6 +226,12 @@ export default function useChatFunctions({
const setSubmissionStart = useSetRecoilState(store.submissionStartFamily(index));
const setShowStopButton = useSetRecoilState(store.showStopButtonByIndex(index));
const focusRegeneratedResponse = useFocusRegeneratedResponse();
+ const getConversation = useGetConversation(index);
+ const addedConversation = useRecoilValue(store.conversationByKeySelector(1));
+ const { modes: codeApprovalModes, selected: fallbackCodeApprovalMode } = useCodeApprovalMode(
+ immutableConversation,
+ addedConversation,
+ );
/**
* Atomically read + reset the per-conversation queue of manually-invoked
@@ -312,6 +320,11 @@ export default function useChatFunctions({
}
const conversation = cloneDeep(immutableConversation);
+ const latestCodeApprovalMode = getConversation()?.codeApprovalMode;
+ const codeApprovalMode =
+ latestCodeApprovalMode != null && codeApprovalModes.includes(latestCodeApprovalMode)
+ ? latestCodeApprovalMode
+ : fallbackCodeApprovalMode;
const endpoint = conversation?.endpoint;
if (endpoint === null) {
@@ -718,6 +731,7 @@ export default function useChatFunctions({
editPrefixLength,
addedConvo,
manualSkills: manualSkills.length > 0 ? manualSkills : undefined,
+ codeApprovalMode,
clientRequestId,
recoverySteerId: overrideRecoverySteerId,
expectedPredecessorCreatedAt: overrideExpectedPredecessorCreatedAt,
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 302e1c9bdd..c910e7ae3e 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -1,4 +1,9 @@
{
+ "com_ui_code_approval_mode": "Code approval mode",
+ "com_ui_code_approval_ask": "Ask before changes",
+ "com_ui_code_approval_ask_description": "Ask before editing files or running commands",
+ "com_ui_code_approval_accept_edits": "Accept edits",
+ "com_ui_code_approval_accept_edits_description": "Allow file edits; continue asking before commands",
"chat_direction_left_to_right": "Left to Right",
"chat_direction_right_to_left": "Right to Left",
"com_a11y_ai_composing": "The AI is still composing.",
diff --git a/e2e/byom/README.md b/e2e/byom/README.md
index cc7dec2d0a..e9f53466ad 100644
--- a/e2e/byom/README.md
+++ b/e2e/byom/README.md
@@ -35,7 +35,8 @@ do not relax that policy to make the test pass.
2. Native SRT capability reported by each worker, plus approved sandboxed Bash.
3. Standalone approved `create_file` physically writes the expected bytes.
4. A subsequent `read_file` returns those bytes through LibreChat.
-5. Approved `edit_file` persists; a browser reload and another turn see the edit.
+5. Selecting **Accept edits** lets `edit_file` persist without a prompt; a browser
+ reload and another turn see the edit, while commands continue to require approval.
6. Rejected creation leaves no file, and creation has no side effect before approval.
7. Selecting worker B does not expose worker A's file; B's write leaves A unchanged.
8. Stopping B produces a persisted tool failure, not success or fallback to A.
@@ -50,7 +51,8 @@ Every run creates its own MongoDB, Redis, Code API, LibreChat, two worker identi
and workspaces. Ports are dynamically assigned, not the usual development ports.
Listeners are loopback-only. No existing database, launchd worker, pairing, or project
directory is reused. Children receive an allowlisted environment; checkout `.env`
-keys are neutralized. Mutations require real UI approval; reads are explicitly allowed.
+keys are neutralized. Mutations default to real UI approval; the test explicitly selects
+**Accept edits** for one file edit, while commands remain approval-gated and reads are allowed.
The command stops its children on success, failure, SIGINT, and SIGTERM. The private
temporary run directory is printed and retained for debugging; it contains test-only
diff --git a/e2e/byom/native.spec.ts b/e2e/byom/native.spec.ts
index fb602f1df2..e24da5f849 100644
--- a/e2e/byom/native.spec.ts
+++ b/e2e/byom/native.spec.ts
@@ -41,6 +41,7 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
const cli = process.env.BYOM_CODE_CLI!;
const workers: Worker[] = [];
let selectedWorker: Worker;
+ let selectedApprovalMode: 'ask' | 'acceptEdits' = 'ask';
const password = `Acceptance-${randomUUID()}`;
const email = `native-${randomUUID()}@example.com`;
const registered = await page.request.post('/api/auth/register', {
@@ -156,6 +157,10 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
},
});
await page.goto(`/c/new?agent_id=${encodeURIComponent(agent.id)}`);
+ await expect(page.getByTestId('code-approval-mode')).toContainText('Ask before changes', {
+ timeout: 30_000,
+ });
+ selectedApprovalMode = 'ask';
}
async function turn(operation: string, decision?: 'Approve' | 'Reject') {
@@ -165,8 +170,17 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
? []
: await requestJson<Message[]>(page, { path: `/api/messages/${id}`, token });
const oldIds = new Set(before.map((message) => message.messageId));
+ const requestPromise = page.waitForRequest((request) => {
+ const pathname = new URL(request.url()).pathname;
+ return (
+ request.method() === 'POST' &&
+ (pathname === '/api/agents/chat' || pathname.startsWith('/api/agents/chat/'))
+ );
+ });
const admitted = await sendMessage(page, `BYOM_ACCEPTANCE:${operation}`);
+ const request = await requestPromise;
expect(admitted.ok()).toBe(true);
+ expect(request.postDataJSON()).toMatchObject({ codeApprovalMode: selectedApprovalMode });
const { conversationId } = (await admitted.json()) as { conversationId: string };
if (decision) {
const card = page.getByTestId('tool-approval').last();
@@ -205,18 +219,31 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
return outputs.join('\n');
}
+ async function selectApprovalMode(mode: 'Ask before changes' | 'Accept edits') {
+ const selector = page.getByTestId('code-approval-mode');
+ await expect(selector).toBeVisible();
+ await selector.click();
+ await expect(selector).toHaveAttribute('aria-expanded', 'true');
+ await page.getByRole('menuitemradio', { name: new RegExp(`^${mode}`) }).click();
+ await expect(selector).toContainText(mode, { timeout: 10_000 });
+ selectedApprovalMode = mode === 'Accept edits' ? 'acceptEdits' : 'ask';
+ }
+
try {
const a = await startWorker('a');
await select(a);
expect(await turn('create', 'Approve')).toContain('Created workspace/proof.txt');
expect(await readFile(path.join(a.root, 'proof.txt'), 'utf8')).toBe('native-original');
expect(await turn('read')).toContain('native-original');
- await turn('edit', 'Approve');
+ await selectApprovalMode('Accept edits');
+ await turn('edit');
expect(await readFile(path.join(a.root, 'proof.txt'), 'utf8')).toBe('native-edited');
await page.reload();
expect(await turn('read')).toContain('native-edited');
+ /** Accept edits does not weaken command execution approval. */
expect(await turn('command', 'Approve')).toContain('native-command-ok');
- expect(await turn('reject', 'Reject')).toMatch(/reject|denied|declined/i);
+ await selectApprovalMode('Ask before changes');
+ expect(await turn('reject', 'Reject')).toMatch(/blocked|reject|denied|declined/i);
expect(await readdir(a.root)).not.toContain('rejected.txt');
const b = await startWorker('b');
@@ -237,6 +264,8 @@ test('native BYOM saves, persists, isolates workers, and fails closed', async ({
body: JSON.stringify({
nativeCommand: true,
physicalCreate: true,
+ acceptEditsWithoutPrompt: true,
+ commandsStillRequireApproval: true,
crossTurnEdit: true,
rejectedWriteAbsent: true,
twoWorkerIsolation: true,
diff --git a/e2e/byom/run.mjs b/e2e/byom/run.mjs
index 426db77c00..64e6b24145 100644
--- a/e2e/byom/run.mjs
+++ b/e2e/byom/run.mjs
@@ -158,7 +158,9 @@ try {
endpoints: {
agents: {
capabilities: ['tools', 'execute_code', 'stateful_code_sessions'],
- toolApproval: { enabled: true, mode: 'default', allow: ['read_file'] },
+ /** BYOM supplies the safe Ask baseline. The endpoint bypass permits a
+ * per-turn Accept edits selection without weakening command approvals. */
+ toolApproval: { enabled: true, mode: 'bypass' },
statefulCodeSessions: {
allowedEnvironments: ['conversation'],
principalWorkers: { enabled: true, maxPerUser: 2 },
@@ -172,7 +174,7 @@ try {
pairing: { allowPrincipalWorkers: true, tokenEnv: 'BYOM_ENROLLMENT_TOKEN' },
configSchema: {
permissions: {
- fileWrite: { allowed: ['ask'], default: 'ask' },
+ fileWrite: { allowed: ['ask', 'allow'], default: 'ask' },
commandExecution: { allowed: ['ask'], default: 'ask' },
},
},
diff --git a/packages/api/src/agents/hitl/byom.spec.ts b/packages/api/src/agents/hitl/byom.spec.ts
index c772ee99ac..36927d46a2 100644
--- a/packages/api/src/agents/hitl/byom.spec.ts
+++ b/packages/api/src/agents/hitl/byom.spec.ts
@@ -5,6 +5,7 @@ import {
collectAttachedCodeEnvironmentAgentIds,
collectAttachedCodeEnvironmentPolicySettings,
createAttachedCodeEnvironmentPolicyHook,
+ resolveAttachedCodeApprovalMode,
} from './byom';
import { canAgentGraphPause } from './admission';
@@ -85,6 +86,122 @@ describe('createAttachedCodeEnvironmentPolicyHook', () => {
).resolves.toMatchObject({ decision: 'deny' });
});
+ test('accept edits allows workspace writes but continues asking for commands', async () => {
+ const settings = new Map<string, AttachedCodeEnvironmentPolicySettings>([
+ [
+ 'attached-agent',
+ {
+ configSchema: {
+ permissions: {
+ fileWrite: { allowed: ['allow', 'ask'], default: 'ask' },
+ commandExecution: { allowed: ['allow', 'ask'], default: 'ask' },
+ },
+ },
+ },
+ ],
+ ]);
+ const mode = resolveAttachedCodeApprovalMode('acceptEdits', settings);
+ const hook = createAttachedCodeEnvironmentPolicyHook(
+ new Set(['attached-agent']),
+ settings,
+ mode,
+ );
+
+ await expect(
+ hook({ toolName: 'write_file', executingAgentId: 'attached-agent' } as never, signal),
+ ).resolves.toEqual({ decision: 'allow' });
+ await expect(
+ hook({ toolName: 'bash_tool', executingAgentId: 'attached-agent' } as never, signal),
+ ).resolves.toMatchObject({ decision: 'ask' });
+ });
+
+ test('rejects accept edits when the attached machine excludes file-write allow', () => {
+ expect(() =>
+ resolveAttachedCodeApprovalMode(
+ 'acceptEdits',
+ new Map([
+ [
+ 'attached-agent',
+ {
+ configSchema: {
+ permissions: { fileWrite: { allowed: ['ask'], default: 'ask' } },
+ },
+ },
+ ],
+ ]),
+ ),
+ ).toThrow('not permitted');
+ });
+
+ test('keeps a restrictive sibling asking without disabling accept edits elsewhere', async () => {
+ const settings = new Map<string, AttachedCodeEnvironmentPolicySettings>([
+ [
+ 'permissive-agent',
+ {
+ configSchema: {
+ permissions: { fileWrite: { allowed: ['allow', 'ask'], default: 'ask' } },
+ },
+ },
+ ],
+ [
+ 'restrictive-agent',
+ {
+ configSchema: {
+ permissions: { fileWrite: { allowed: ['ask'], default: 'ask' } },
+ },
+ },
+ ],
+ ]);
+ const mode = resolveAttachedCodeApprovalMode('acceptEdits', settings);
+ const hook = createAttachedCodeEnvironmentPolicyHook(
+ new Set(['permissive-agent', 'restrictive-agent']),
+ settings,
+ mode,
+ );
+
+ await expect(
+ hook({ toolName: 'write_file', executingAgentId: 'permissive-agent' } as never, signal),
+ ).resolves.toEqual({ decision: 'allow' });
+ await expect(
+ hook({ toolName: 'write_file', executingAgentId: 'restrictive-agent' } as never, signal),
+ ).resolves.toMatchObject({ decision: 'ask' });
+ });
+
+ test('applies a restrictive policy discovered after lazy agent resolution', async () => {
+ const attachedIds = new Set<string>(['eager-agent']);
+ const settings = new Map<string, AttachedCodeEnvironmentPolicySettings>([
+ [
+ 'eager-agent',
+ {
+ configSchema: {
+ permissions: { fileWrite: { allowed: ['allow', 'ask'], default: 'ask' } },
+ },
+ },
+ ],
+ ]);
+ const mode = resolveAttachedCodeApprovalMode('acceptEdits', settings);
+ const hook = createAttachedCodeEnvironmentPolicyHook(attachedIds, settings, mode);
+
+ attachedIds.add('lazy-agent');
+ settings.set('lazy-agent', {
+ configSchema: {
+ permissions: { fileWrite: { allowed: ['ask'], default: 'ask' } },
+ },
+ });
+
+ await expect(
+ hook({ toolName: 'write_file', executingAgentId: 'lazy-agent' } as never, signal),
+ ).resolves.toMatchObject({ decision: 'ask' });
+ });
+
+ test('rejects an explicit mode when approvals are disabled by the administrator', () => {
+ expect(resolveAttachedCodeApprovalMode('ask', new Map(), false)).toBeUndefined();
+ expect(() => resolveAttachedCodeApprovalMode('acceptEdits', new Map(), false)).toThrow(
+ 'not permitted',
+ );
+ expect(resolveAttachedCodeApprovalMode(undefined, new Map(), false)).toBeUndefined();
+ });
+
test.each(['create_file', 'edit_file'])(
'keeps persistent skill write %s approval-gated when BYOM file writes are allowed',
async (toolName) => {
diff --git a/packages/api/src/agents/hitl/byom.ts b/packages/api/src/agents/hitl/byom.ts
index a07e6add9b..e8adf90da8 100644
--- a/packages/api/src/agents/hitl/byom.ts
+++ b/packages/api/src/agents/hitl/byom.ts
@@ -1,5 +1,12 @@
import { Constants } from '@librechat/agents';
+import {
+ CODE_APPROVAL_MODES,
+ getAllowedCodeApprovalModes,
+ resolveCodeApprovalMode,
+ resolveCodePermissionDecision,
+} from 'librechat-data-provider';
import type {
+ CodeApprovalMode,
CodeEnvironmentPermissionDecision,
CodeEnvironmentUserConfigSchema,
CodeEnvironmentUserSettings,
@@ -127,12 +134,62 @@ export function collectAttachedCodeEnvironmentPolicySettings(
function permissionDecision(
policy: AttachedCodeEnvironmentPolicySettings | undefined,
category: PermissionCategory,
+ mode?: CodeApprovalMode,
): CodeEnvironmentPermissionDecision {
const field = policy?.configSchema?.permissions?.[category];
const configuredDecision = policy?.settings?.permissions?.[category];
- return configuredDecision != null && field?.allowed.includes(configuredDecision) === true
- ? configuredDecision
- : (field?.default ?? 'ask');
+ const decision =
+ configuredDecision != null && field?.allowed.includes(configuredDecision) === true
+ ? configuredDecision
+ : (field?.default ?? 'ask');
+ const effectiveMode = getAllowedCodeApprovalModes({
+ environment: 'attached',
+ allowedModes: CODE_APPROVAL_MODES,
+ configSchema: policy?.configSchema,
+ settings: policy?.settings,
+ }).includes(mode ?? 'ask')
+ ? mode
+ : undefined;
+ return resolveCodePermissionDecision({ mode: effectiveMode, category, decision });
+}
+
+export function resolveAttachedCodeApprovalMode(
+ requested: unknown,
+ settingsByAgentId: ReadonlyMap<string, AttachedCodeEnvironmentPolicySettings>,
+ approvalsEnabled = true,
+): CodeApprovalMode | undefined {
+ if (!approvalsEnabled) {
+ if (requested === 'ask') {
+ return undefined;
+ }
+ return resolveCodeApprovalMode(requested, {
+ environment: 'attached',
+ allowedModes: [],
+ enabled: false,
+ });
+ }
+ let resolved: CodeApprovalMode | undefined;
+ let rejection: Error | undefined;
+ for (const policy of settingsByAgentId.values()) {
+ try {
+ resolved = resolveCodeApprovalMode(requested, {
+ environment: 'attached',
+ allowedModes: CODE_APPROVAL_MODES,
+ configSchema: policy.configSchema,
+ settings: policy.settings,
+ });
+ } catch (error) {
+ rejection = error as Error;
+ }
+ }
+ if (resolved == null && rejection != null) throw rejection;
+ return (
+ resolved ??
+ resolveCodeApprovalMode(requested, {
+ environment: 'attached',
+ allowedModes: CODE_APPROVAL_MODES,
+ })
+ );
}
function exactToolMatcher(toolNames: ReadonlySet<string>): string {
@@ -143,16 +200,18 @@ function exactToolMatcher(toolNames: ReadonlySet<string>): string {
export function buildAttachedCodeEnvironmentAdmissionHooks(
attachedAgentIds: ReadonlySet<string>,
settingsByAgentId: ReadonlyMap<string, AttachedCodeEnvironmentPolicySettings> = new Map(),
+ mode?: CodeApprovalMode,
): ResolvedToolApprovalHook[] {
- const hook = createAttachedCodeEnvironmentPolicyHook(attachedAgentIds, settingsByAgentId);
+ const hook = createAttachedCodeEnvironmentPolicyHook(attachedAgentIds, settingsByAgentId, mode);
const hooks: ResolvedToolApprovalHook[] = [];
const askFileAgents = new Set<string>();
const askCommandAgents = new Set<string>();
const skillAuthoringAgents = new Set<string>();
for (const agentId of attachedAgentIds) {
const policy = settingsByAgentId.get(agentId);
- if (permissionDecision(policy, 'fileWrite') === 'ask') askFileAgents.add(agentId);
- if (permissionDecision(policy, 'commandExecution') === 'ask') askCommandAgents.add(agentId);
+ if (permissionDecision(policy, 'fileWrite', mode) === 'ask') askFileAgents.add(agentId);
+ if (permissionDecision(policy, 'commandExecution', mode) === 'ask')
+ askCommandAgents.add(agentId);
if (policy?.skillAuthoringAvailable === true) skillAuthoringAgents.add(agentId);
}
if (askFileAgents.size > 0) {
@@ -183,6 +242,7 @@ export function buildAttachedCodeEnvironmentAdmissionHooks(
export function createAttachedCodeEnvironmentPolicyHook(
attachedAgentIds: ReadonlySet<string>,
settingsByAgentId: ReadonlyMap<string, AttachedCodeEnvironmentPolicySettings> = new Map(),
+ mode?: CodeApprovalMode,
): HookCallback<'PreToolUse'> {
return async (input) => {
let category: PermissionCategory | undefined;
@@ -215,7 +275,11 @@ export function createAttachedCodeEnvironmentPolicyHook(
reason: `${input.toolName} could not be attributed to an attached code environment`,
};
}
- const decision = permissionDecision(settingsByAgentId.get(input.executingAgentId), category);
+ const decision = permissionDecision(
+ settingsByAgentId.get(input.executingAgentId),
+ category,
+ mode,
+ );
if (decision === 'allow') {
return { decision };
}
diff --git a/packages/api/src/agents/hitl/policy.spec.ts b/packages/api/src/agents/hitl/policy.spec.ts
index f234b68876..f05be9fa1f 100644
--- a/packages/api/src/agents/hitl/policy.spec.ts
+++ b/packages/api/src/agents/hitl/policy.spec.ts
@@ -647,6 +647,12 @@ describe('computeAgentRequestFingerprint', () => {
expect(computeAgentRequestFingerprint(base)).not.toBe(
computeAgentRequestFingerprint({ ...base, agent_id: 'agent-2' }),
);
+ expect(computeAgentRequestFingerprint(base)).not.toBe(
+ computeAgentRequestFingerprint({ ...base, codeApprovalMode: 'acceptEdits' }),
+ );
+ expect(computeAgentRequestFingerprint(base)).not.toBe(
+ computeAgentRequestFingerprint({ ...base, codeApprovalMode: null }),
+ );
});
it('differs when promptPrefix changes (ephemeral instructions)', () => {
@@ -700,6 +706,7 @@ describe('pickResumeContext / applyResumeContext', () => {
manualSkills: ['code-reviewer'],
// Graph-determining: feeds the ephemeral agent id / checkpoint namespace (#14253).
modelLabel: 'My Opus',
+ codeApprovalMode: 'acceptEdits',
conversationId: 'c',
decisions: [],
actionId: 'x',
@@ -714,9 +721,26 @@ describe('pickResumeContext / applyResumeContext', () => {
timezone: 'America/New_York',
manualSkills: ['code-reviewer'],
modelLabel: 'My Opus',
+ codeApprovalMode: 'acceptEdits',
});
});
+ it('pins code approval mode across resume and removes a forged upgrade', () => {
+ const restored: Record<string, unknown> = {
+ conversationId: 'c',
+ codeApprovalMode: 'acceptEdits',
+ };
+ applyResumeContext(restored, { endpoint: 'agents', codeApprovalMode: 'ask' });
+ expect(restored.codeApprovalMode).toBe('ask');
+
+ const injected: Record<string, unknown> = {
+ conversationId: 'c',
+ codeApprovalMode: 'acceptEdits',
+ };
+ applyResumeContext(injected, { endpoint: 'agents' });
+ expect('codeApprovalMode' in injected).toBe(false);
+ });
+
it('replays a dropped modelLabel so the ephemeral agent id stays stable (#14253)', () => {
// Resume/reload case: the resolved llmConfig stripped modelLabel; the server restores
// the original top-level value so parseCompactConvo re-derives the same sender/id.
diff --git a/packages/api/src/agents/hitl/policy.ts b/packages/api/src/agents/hitl/policy.ts
index 95ee5f40ff..371e7441b2 100644
--- a/packages/api/src/agents/hitl/policy.ts
+++ b/packages/api/src/agents/hitl/policy.ts
@@ -358,6 +358,7 @@ export interface AgentRequestFingerprintFields {
/** Ephemeral agents derive their system instructions from this; pin it too. */
promptPrefix?: string | null;
ephemeralAgent?: Record<string, unknown> | null;
+ codeApprovalMode?: string | null;
}
/** Stable, order-independent serialization of the ephemeral capability config. */
@@ -395,6 +396,7 @@ export const RESUME_CONTEXT_KEYS = [
'model',
'promptPrefix',
'ephemeralAgent',
+ 'codeApprovalMode',
// The agents build reads addedConvo into endpointOption to add parallel/secondary
// agents; the resume POST can't reconstruct it, so replay it from the paused request.
'addedConvo',
@@ -729,6 +731,9 @@ export function computeAgentRequestFingerprint(fields: AgentRequestFingerprintFi
spec: fields.spec ?? null,
promptPrefix: fields.promptPrefix ?? null,
ephemeralAgent: normalizeEphemeralAgent(fields.ephemeralAgent),
+ ...(Object.prototype.hasOwnProperty.call(fields, 'codeApprovalMode')
+ ? { codeApprovalMode: fields.codeApprovalMode ?? null }
+ : {}),
});
return createHash('sha256').update(canonical).digest('hex');
}
diff --git a/packages/api/src/agents/run.ts b/packages/api/src/agents/run.ts
index 28ff2dc40c..5a03ce9f41 100644
--- a/packages/api/src/agents/run.ts
+++ b/packages/api/src/agents/run.ts
@@ -35,6 +35,7 @@ import type {
} from '@librechat/agents';
import type {
Agent,
+ CodeApprovalMode,
TAgentsEndpoint,
AgentModelParameters,
AgentSubagentsConfig,
@@ -62,6 +63,7 @@ import {
collectAttachedCodeEnvironmentAgentIds,
collectAttachedCodeEnvironmentPolicySettings,
createAttachedCodeEnvironmentPolicyHook,
+ resolveAttachedCodeApprovalMode,
} from '~/agents/hitl/byom';
import {
CHECK_BACKGROUND_TASK_NAME,
@@ -1551,6 +1553,7 @@ export async function createRun({
messages,
discoveredToolNames,
requestBody,
+ codeApprovalMode: requestedCodeApprovalMode,
user,
tenantId,
centralTraceExportEnabled,
@@ -1589,6 +1592,7 @@ export async function createRun({
streaming?: boolean;
streamUsage?: boolean;
requestBody?: t.RequestBody;
+ codeApprovalMode?: CodeApprovalMode;
user?: IUser;
tenantId?: string;
/**
@@ -1975,6 +1979,11 @@ export async function createRun({
const agentsEndpointConfig = appConfig?.endpoints?.[EModelEndpoint.agents];
const attachedCodeEnvironmentAgentIds = collectAttachedCodeEnvironmentAgentIds(agents);
const attachedCodeEnvironmentSettings = collectAttachedCodeEnvironmentPolicySettings(agents);
+ const codeApprovalMode = resolveAttachedCodeApprovalMode(
+ requestedCodeApprovalMode,
+ attachedCodeEnvironmentSettings,
+ agentsEndpointConfig?.toolApproval?.enabled !== false,
+ );
assertAttachedCodeEnvironmentApprovalSupported({
hasAttachedCodeEnvironment: attachedCodeEnvironmentAgentIds.size > 0,
hitlCapable,
@@ -2133,6 +2142,7 @@ export async function createRun({
hook: createAttachedCodeEnvironmentPolicyHook(
attachedCodeEnvironmentAgentIds,
attachedCodeEnvironmentSettings,
+ codeApprovalMode,
),
},
]
@@ -2142,6 +2152,9 @@ export async function createRun({
: undefined;
registerResolvedMCPToolAliases = (resolvedAgent) => {
if (resolvedAgent.codeExecutionContext?.environmentType === 'attached') {
+ // The admission hook closes over these collections. A lazily resolved agent
+ // therefore receives its own current machine policy before its first tool call;
+ // a mode that machine does not permit safely falls back to ask/deny there.
attachedCodeEnvironmentAgentIds.add(resolvedAgent.id);
attachedCodeEnvironmentSettings.set(resolvedAgent.id, {
configSchema: resolvedAgent.codeExecutionContext.codeEnvironmentConfigSchema,
diff --git a/packages/api/src/endpoints/config/endpoints.spec.ts b/packages/api/src/endpoints/config/endpoints.spec.ts
index a354eca818..4a670226cc 100644
--- a/packages/api/src/endpoints/config/endpoints.spec.ts
+++ b/packages/api/src/endpoints/config/endpoints.spec.ts
@@ -186,6 +186,7 @@ describe('createEndpointsConfigService', () => {
appConfig({
endpoints: {
[EModelEndpoint.agents]: {
+ toolApproval: { enabled: false },
statefulCodeSessions: {
allowedEnvironments: ['user', 'agent-user'],
environments: [
@@ -219,6 +220,8 @@ describe('createEndpointsConfigService', () => {
expect(result?.[EModelEndpoint.agents]?.statefulCodeSessions).toEqual({
allowedEnvironments: ['user', 'agent-user'],
+ approvalsEnabled: false,
+ approvalModes: [],
environments: [
{
id: 'attached-vm',
@@ -270,10 +273,45 @@ describe('createEndpointsConfigService', () => {
expect(result?.[EModelEndpoint.agents]?.statefulCodeSessions).toEqual({
allowedEnvironments: ['user'],
+ approvalsEnabled: true,
+ approvalModes: ['ask', 'acceptEdits'],
environments: [],
});
});
+ it.each([
+ [{ enabled: true }, ['ask']],
+ [{ enabled: true, mode: 'default' }, ['ask']],
+ [{ enabled: true, mode: 'dontAsk' }, ['ask']],
+ [{ enabled: true, mode: 'bypass' }, ['ask', 'acceptEdits']],
+ ])('exposes approval modes allowed by endpoint policy %p', async (toolApproval, expected) => {
+ const deps = createMockDeps({
+ loadDefaultEndpointsConfig: jest.fn().mockResolvedValue({
+ [EModelEndpoint.agents]: { userProvide: false, order: 0 },
+ }),
+ getAppConfig: jest.fn().mockResolvedValue(
+ appConfig({
+ endpoints: {
+ [EModelEndpoint.agents]: {
+ toolApproval,
+ statefulCodeSessions: {
+ allowedEnvironments: ['user'],
+ environments: [],
+ },
+ },
+ },
+ }),
+ ),
+ });
+ const { getEndpointsConfig } = createEndpointsConfigService(deps);
+
+ const result = await getEndpointsConfig(fakeReq());
+
+ expect(result?.[EModelEndpoint.agents]?.statefulCodeSessions?.approvalModes).toEqual(
+ expected,
+ );
+ });
+
it('merges bedrock availableRegions', async () => {
const deps = createMockDeps({
loadDefaultEndpointsConfig: jest.fn().mockResolvedValue({
diff --git a/packages/api/src/endpoints/config/endpoints.ts b/packages/api/src/endpoints/config/endpoints.ts
index 156fa091ce..746f00955b 100644
--- a/packages/api/src/endpoints/config/endpoints.ts
+++ b/packages/api/src/endpoints/config/endpoints.ts
@@ -1,5 +1,6 @@
import {
AuthType,
+ CODE_APPROVAL_MODES,
EModelEndpoint,
isAgentsEndpoint,
orderEndpointsConfig,
@@ -72,9 +73,21 @@ export function createEndpointsConfigService(deps: EndpointsConfigDeps): {
if (mergedConfig[EModelEndpoint.agents] && appConfig?.endpoints?.[EModelEndpoint.agents]) {
const { disableBuilder, capabilities, allowedProviders, statefulCodeSessions, maxSubagents } =
appConfig.endpoints[EModelEndpoint.agents];
+ const toolApproval = appConfig.endpoints[EModelEndpoint.agents].toolApproval;
+ /** Only advertise Accept edits when the endpoint fallback cannot force every
+ * unmatched tool back to Ask/Deny. Explicit rules and hooks remain free to
+ * tighten individual actions after the user selects the broader mode. */
+ let approvalModes = [...CODE_APPROVAL_MODES];
+ if (toolApproval?.enabled === false) {
+ approvalModes = [];
+ } else if (toolApproval?.enabled === true && toolApproval.mode !== 'bypass') {
+ approvalModes = ['ask'];
+ }
const clientStatefulCodeSessions = statefulCodeSessions
? {
allowedEnvironments: statefulCodeSessions.allowedEnvironments,
+ approvalsEnabled: toolApproval?.enabled !== false,
+ approvalModes,
environments: statefulCodeSessions.environments
?.filter(
(environment) =>
diff --git a/packages/api/src/middleware/code.spec.ts b/packages/api/src/middleware/code.spec.ts
index fbb094b6b6..25947f8448 100644
--- a/packages/api/src/middleware/code.spec.ts
+++ b/packages/api/src/middleware/code.spec.ts
@@ -24,27 +24,23 @@ type LimiterOptions = {
};
describe('code environment limiters', () => {
- beforeEach(() => {
- jest.clearAllMocks();
- });
-
test('uses a bounded per-user pairing bucket', () => {
- const req = { user: { id: 'user-1' } } as Request;
+ const req = { user: { id: 'user-1' } } as unknown as Request;
codeEnvironmentPairingLimiter(req, {} as Response, jest.fn());
- const options = mockRateLimit.mock.calls.at(-1)?.[0] as LimiterOptions;
+ const options = mockRateLimit.mock.calls[0]?.[0] as LimiterOptions;
expect(options).toEqual(expect.objectContaining({ max: 5, windowMs: 3_600_000 }));
expect(options.keyGenerator(req)).toBe('user-1');
expect(mockLimiterCache).toHaveBeenCalledWith('code_environment_pairing_user_limiter');
});
test('keys status user limits by immutable user ID', () => {
- const req = { user: { id: 'user-1' }, ip: '2001:db8::1' } as Request;
+ const req = { user: { id: 'user-1' }, ip: '2001:db8::1' } as unknown as Request;
codeEnvironmentStatusLimiter(req, {} as Response, jest.fn());
- const options = mockRateLimit.mock.calls.at(-1)?.[0] as LimiterOptions;
+ const options = mockRateLimit.mock.calls[1]?.[0] as LimiterOptions;
expect(options).toEqual(expect.objectContaining({ max: 120, windowMs: 60_000 }));
expect(options.keyGenerator(req)).toBe('user-1');
expect(mockIpKeyGenerator).not.toHaveBeenCalled();
@@ -52,11 +48,11 @@ describe('code environment limiters', () => {
});
test('applies an independent normalized IP status limit', () => {
- const req = { user: { id: 'user-1' }, ip: '2001:db8::1' } as Request;
+ const req = { user: { id: 'user-1' }, ip: '2001:db8::1' } as unknown as Request;
codeEnvironmentStatusIpLimiter(req, {} as Response, jest.fn());
- const options = mockRateLimit.mock.calls.at(-1)?.[0] as LimiterOptions;
+ const options = mockRateLimit.mock.calls[2]?.[0] as LimiterOptions;
expect(options).toEqual(expect.objectContaining({ max: 300, windowMs: 60_000 }));
expect(options.keyGenerator(req)).toBe('2001:db8::1');
expect(mockIpKeyGenerator).toHaveBeenCalledWith('2001:db8::1');
diff --git a/packages/api/src/middleware/code.ts b/packages/api/src/middleware/code.ts
index 205b617145..8ef21487a3 100644
--- a/packages/api/src/middleware/code.ts
+++ b/packages/api/src/middleware/code.ts
@@ -1,86 +1,70 @@
import { rateLimit, ipKeyGenerator } from 'express-rate-limit';
+import type { AugmentedRequest } from 'express-rate-limit';
import type { Request, RequestHandler } from 'express';
import { limiterCache } from '~/cache/cacheFactory';
type AuthenticatedRequest = Request & { user?: { id?: string } };
-let configuredPairingLimiter: RequestHandler | undefined;
-let configuredStatusIpLimiter: RequestHandler | undefined;
-let configuredStatusLimiter: RequestHandler | undefined;
-
function positiveInteger(value: string | undefined, fallback: number): number {
const parsed = Number(value);
return Number.isSafeInteger(parsed) && parsed >= 1 ? parsed : fallback;
}
-export const codeEnvironmentPairingLimiter: RequestHandler = (req, res, next) => {
- if (configuredPairingLimiter == null) {
- const max = positiveInteger(process.env.CODE_ENVIRONMENT_PAIRING_USER_MAX, 5);
- const windowInMinutes = positiveInteger(process.env.CODE_ENVIRONMENT_PAIRING_USER_WINDOW, 60);
- configuredPairingLimiter = rateLimit({
- windowMs: windowInMinutes * 60 * 1000,
- max,
- handler: (limitedReq, limitedRes) => {
- const resetAt = limitedReq.rateLimit?.resetTime?.getTime?.();
- const retryAfterSeconds = Number.isFinite(resetAt)
- ? Math.max(1, Math.ceil((resetAt - Date.now()) / 1000))
- : Math.max(1, Math.ceil(windowInMinutes * 60));
- limitedRes.set('Retry-After', String(retryAfterSeconds));
- return limitedRes.status(429).json({
- error: {
- code: 'code_environment_pairing_rate_limited',
- message: 'Code environment pairing rate limit exceeded.',
- type: 'rate_limit_error',
- },
- });
+const pairingWindowInMinutes = positiveInteger(
+ process.env.CODE_ENVIRONMENT_PAIRING_USER_WINDOW,
+ 60,
+);
+export const codeEnvironmentPairingLimiter: RequestHandler = rateLimit({
+ windowMs: pairingWindowInMinutes * 60 * 1000,
+ max: positiveInteger(process.env.CODE_ENVIRONMENT_PAIRING_USER_MAX, 5),
+ handler: (limitedReq, limitedRes) => {
+ const resetAt = (limitedReq as AugmentedRequest).rateLimit?.resetTime?.getTime();
+ const retryAfterSeconds =
+ typeof resetAt === 'number' && Number.isFinite(resetAt)
+ ? Math.max(1, Math.ceil((resetAt - Date.now()) / 1000))
+ : Math.max(1, Math.ceil(pairingWindowInMinutes * 60));
+ limitedRes.set('Retry-After', String(retryAfterSeconds));
+ return limitedRes.status(429).json({
+ error: {
+ code: 'code_environment_pairing_rate_limited',
+ message: 'Code environment pairing rate limit exceeded.',
+ type: 'rate_limit_error',
},
- keyGenerator: (limitedReq) => String((limitedReq as AuthenticatedRequest).user?.id ?? ''),
- store: limiterCache('code_environment_pairing_user_limiter'),
});
- }
- return configuredPairingLimiter(req, res, next);
-};
+ },
+ keyGenerator: (limitedReq) => String((limitedReq as AuthenticatedRequest).user?.id ?? ''),
+ store: limiterCache('code_environment_pairing_user_limiter'),
+});
-export const codeEnvironmentStatusLimiter: RequestHandler = (req, res, next) => {
- if (configuredStatusLimiter == null) {
- const max = positiveInteger(process.env.CODE_ENVIRONMENT_STATUS_USER_MAX, 120);
- const windowInMinutes = positiveInteger(process.env.CODE_ENVIRONMENT_STATUS_USER_WINDOW, 1);
- configuredStatusLimiter = rateLimit({
- windowMs: windowInMinutes * 60 * 1000,
- max,
- handler: (_limitedReq, limitedRes) =>
- limitedRes.status(429).json({
- error: {
- code: 'code_environment_status_rate_limited',
- message: 'Code environment status rate limit exceeded.',
- type: 'rate_limit_error',
- },
- }),
- keyGenerator: (limitedReq) => String((limitedReq as AuthenticatedRequest).user?.id ?? ''),
- store: limiterCache('code_environment_status_user_limiter'),
- });
- }
- return configuredStatusLimiter(req, res, next);
-};
+export const codeEnvironmentStatusLimiter: RequestHandler = rateLimit({
+ windowMs: positiveInteger(process.env.CODE_ENVIRONMENT_STATUS_USER_WINDOW, 1) * 60 * 1000,
+ max: positiveInteger(process.env.CODE_ENVIRONMENT_STATUS_USER_MAX, 120),
+ handler: (_limitedReq, limitedRes) =>
+ limitedRes.status(429).json({
+ error: {
+ code: 'code_environment_status_rate_limited',
+ message: 'Code environment status rate limit exceeded.',
+ type: 'rate_limit_error',
+ },
+ }),
+ keyGenerator: (limitedReq) => String((limitedReq as AuthenticatedRequest).user?.id ?? ''),
+ store: limiterCache('code_environment_status_user_limiter'),
+});
-export const codeEnvironmentStatusIpLimiter: RequestHandler = (req, res, next) => {
- if (configuredStatusIpLimiter == null) {
- const max = positiveInteger(process.env.CODE_ENVIRONMENT_STATUS_IP_MAX, 300);
- const windowInMinutes = positiveInteger(process.env.CODE_ENVIRONMENT_STATUS_IP_WINDOW, 1);
- configuredStatusIpLimiter = rateLimit({
- windowMs: windowInMinutes * 60 * 1000,
- max,
- handler: (_limitedReq, limitedRes) =>
- limitedRes.status(429).json({
- error: {
- code: 'code_environment_status_rate_limited',
- message: 'Code environment status rate limit exceeded.',
- type: 'rate_limit_error',
- },
- }),
- keyGenerator: (limitedReq) => ipKeyGenerator(limitedReq.ip),
- store: limiterCache('code_environment_status_ip_limiter'),
- });
- }
- return configuredStatusIpLimiter(req, res, next);
-};
+export const codeEnvironmentStatusIpLimiter: RequestHandler = rateLimit({
+ windowMs: positiveInteger(process.env.CODE_ENVIRONMENT_STATUS_IP_WINDOW, 1) * 60 * 1000,
+ max: positiveInteger(process.env.CODE_ENVIRONMENT_STATUS_IP_MAX, 300),
+ handler: (_limitedReq, limitedRes) =>
+ limitedRes.status(429).json({
+ error: {
+ code: 'code_environment_status_rate_limited',
+ message: 'Code environment status rate limit exceeded.',
+ type: 'rate_limit_error',
+ },
+ }),
+ keyGenerator: (limitedReq) => {
+ const ip = limitedReq.ip ?? limitedReq.socket.remoteAddress;
+ return ip == null ? 'unknown' : ipKeyGenerator(ip);
+ },
+ store: limiterCache('code_environment_status_ip_limiter'),
+});
diff --git a/packages/api/src/types/http.ts b/packages/api/src/types/http.ts
index f9ccb5dddf..1618b6e7a4 100644
--- a/packages/api/src/types/http.ts
+++ b/packages/api/src/types/http.ts
@@ -1,5 +1,5 @@
+import type { CodeApprovalMode, TEndpointOption } from 'librechat-data-provider';
import type { IUser, AppConfig, IConversation } from '@librechat/data-schemas';
-import type { TEndpointOption } from 'librechat-data-provider';
import type { Request } from 'express';
/**
@@ -18,6 +18,7 @@ export type RequestBody = {
endpointOption?: Partial<TEndpointOption>;
/** Browser IANA timezone used to resolve local-time prompt variables (e.g. `{{current_datetime}}`). */
timezone?: string;
+ codeApprovalMode?: CodeApprovalMode;
};
export type ServerRequest = Request<unknown, unknown, RequestBody> & {
diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.ts
index fe9278d655..71c8831861 100644
--- a/packages/data-provider/src/types.ts
+++ b/packages/data-provider/src/types.ts
@@ -609,6 +609,9 @@ export type TConfig = {
statefulCodeSessions?: {
allowedEnvironments: StatefulCodeEnvironment[];
environments?: TPublicCodeEnvironment[];
+ approvalsEnabled?: boolean;
+ /** Approval modes the endpoint policy permits the client to offer. */
+ approvalModes?: CodeApprovalMode[];
};
/** Effective subagents-per-agent cap served from `endpoints.agents.maxSubagents`. */
maxSubagents?: number;
diff --git a/packages/data-schemas/src/schema/defaults.ts b/packages/data-schemas/src/schema/defaults.ts
index 1f11dc19e9..9d390ea2d6 100644
--- a/packages/data-schemas/src/schema/defaults.ts
+++ b/packages/data-schemas/src/schema/defaults.ts
@@ -1,4 +1,5 @@
import { Schema } from 'mongoose';
+import { CODE_APPROVAL_MODES } from 'librechat-data-provider';
// @ts-ignore
export const conversationPreset: {
@@ -116,6 +117,10 @@ export const conversationPreset: {
agent_id: {
type: StringConstructor;
};
+ codeApprovalMode: {
+ type: StringConstructor;
+ enum: string[];
+ };
/* assistants */
assistant_id: {
type: StringConstructor;
@@ -299,6 +304,10 @@ export const conversationPreset: {
agent_id: {
type: String,
},
+ codeApprovalMode: {
+ type: String,
+ enum: [...CODE_APPROVAL_MODES],
+ },
/* assistants */
assistant_id: {
type: String,
diff --git a/packages/data-schemas/src/types/convo.ts b/packages/data-schemas/src/types/convo.ts
index cabdd1371f..f149ce6b97 100644
--- a/packages/data-schemas/src/types/convo.ts
+++ b/packages/data-schemas/src/types/convo.ts
@@ -1,4 +1,4 @@
-import type { TSubagentThreadLineage } from 'librechat-data-provider';
+import type { CodeApprovalMode, TSubagentThreadLineage } from 'librechat-data-provider';
import type { Document, Types } from 'mongoose';
import type { ICompactionSemanticIndexProjection } from './compaction';
@@ -264,6 +264,7 @@ export interface IConversation extends Document {
resendFiles?: boolean;
imageDetail?: string;
agent_id?: string;
+ codeApprovalMode?: CodeApprovalMode;
/** Immutable primary persisted-agent attribution for Insights. */
initial_agent_id?: string | null;
subagentThread?: TSubagentThreadLineage;