Skip to content

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

🟰 fix: Normalize File Edits Before Approval (#16543)

lia-by-librechat[bot]210086aa49dc
diff --git a/packages/api/src/agents/edits.spec.ts b/packages/api/src/agents/edits.spec.ts
new file mode 100644
index 0000000000..d57ab540ae
--- /dev/null
+++ b/packages/api/src/agents/edits.spec.ts
@@ -0,0 +1,52 @@
+import { normalizeEditArgs } from './edits';
+
+describe('normalizeEditArgs', () => {
+ test.each(
+ [
+ [],
+ '[]',
+ null,
+ undefined,
+ {},
+ { old_text: 'original', new_text: 'replacement' },
+ 'not json',
+ 'null',
+ 1,
+ true,
+ [null],
+ [[]],
+ [{ old_text: 'original' }],
+ [{ old_text: '', new_text: 'replacement' }],
+ [{ old_text: 'original', new_text: 'replacement', replace_all: 'yes' }],
+ ].map((edits) => [edits]),
+ )('rejects supplied invalid edits %# instead of using top-level replacements', (edits) => {
+ expect(typeof normalizeEditArgs({ edits, old_text: 'original', new_text: 'replacement' })).toBe(
+ 'string',
+ );
+ });
+
+ test('normalizes a single replacement without changing the input', () => {
+ const args = { old_text: 'original', new_text: '', replace_all: 'true' };
+ expect(normalizeEditArgs(args)).toEqual([
+ { old_text: 'original', new_text: '', replace_all: true },
+ ]);
+ expect(args.replace_all).toBe('true');
+ });
+
+ test.each(
+ [
+ [{ old_text: 'batch', new_text: 'replacement', replace_all: 'false' }],
+ JSON.stringify([{ old_text: 'batch', new_text: 'replacement', replace_all: 'false' }]),
+ [JSON.stringify({ old_text: 'batch', new_text: 'replacement', replace_all: 'false' })],
+ ].map((edits) => [edits]),
+ )('normalizes valid batches %# and never selects ignored top-level fields', (edits) => {
+ const normalized = normalizeEditArgs({
+ edits,
+ old_text: 'ignored',
+ new_text: 'ignored',
+ replace_all: true,
+ });
+ expect(normalized).toEqual([{ old_text: 'batch', new_text: 'replacement' }]);
+ expect(normalizeEditArgs({ edits: normalized })).toEqual(normalized);
+ });
+});
diff --git a/packages/api/src/agents/edits.ts b/packages/api/src/agents/edits.ts
new file mode 100644
index 0000000000..23e32a060b
--- /dev/null
+++ b/packages/api/src/agents/edits.ts
@@ -0,0 +1,76 @@
+export type TextEdit = {
+ old_text: string;
+ new_text: string;
+ /** Replaces every location instead of requiring exactly one. */
+ replace_all?: boolean;
+};
+
+/* Models often stringify nested JSON (JSON-in-JSON) instead of passing a
+ real array/object, which would otherwise fail validation and cost a retry
+ round-trip. Parse a JSON string back to its value; leave non-strings and
+ unparseable strings untouched so the explicit errors below still fire. */
+function coerceJsonValue(value: unknown): unknown {
+ if (typeof value !== 'string') {
+ return value;
+ }
+ try {
+ return JSON.parse(value);
+ } catch {
+ return value;
+ }
+}
+
+/** `replace_all` as a boolean, tolerating the stringified form some models send. */
+function normalizeReplaceAll(value: unknown): boolean | undefined | string {
+ if (value === true || value === 'true') return true;
+ if (value === undefined || value === null || value === false || value === 'false') {
+ return undefined;
+ }
+ return 'replace_all must be true or false.';
+}
+
+function textEdit(oldText: string, newText: string, rawReplaceAll: unknown): TextEdit | string {
+ if (oldText.length === 0) {
+ return 'old_text cannot be empty.';
+ }
+ const replaceAll = normalizeReplaceAll(rawReplaceAll);
+ if (typeof replaceAll === 'string') return replaceAll;
+ return replaceAll
+ ? { old_text: oldText, new_text: newText, replace_all: true }
+ : { old_text: oldText, new_text: newText };
+}
+
+export function normalizeEditArgs(args: {
+ old_text?: unknown;
+ new_text?: unknown;
+ replace_all?: unknown;
+ edits?: unknown;
+}): TextEdit[] | string {
+ if (Object.prototype.hasOwnProperty.call(args, 'edits')) {
+ const coercedEdits = coerceJsonValue(args.edits);
+ if (!Array.isArray(coercedEdits) || coercedEdits.length === 0) {
+ return 'Provide a non-empty edits array when edits is supplied.';
+ }
+ const edits: TextEdit[] = [];
+ for (const rawEdit of coercedEdits) {
+ const edit = coerceJsonValue(rawEdit);
+ if (!edit || typeof edit !== 'object' || Array.isArray(edit)) {
+ return 'Each edit must be an object with old_text and new_text.';
+ }
+ const entry = edit as { old_text?: unknown; new_text?: unknown; replace_all?: unknown };
+ if (typeof entry.old_text !== 'string' || typeof entry.new_text !== 'string') {
+ return 'Each edit requires string old_text and new_text.';
+ }
+ const normalized = textEdit(entry.old_text, entry.new_text, entry.replace_all);
+ if (typeof normalized === 'string') return normalized;
+ edits.push(normalized);
+ }
+ return edits;
+ }
+
+ if (typeof args.old_text !== 'string' || typeof args.new_text !== 'string') {
+ return 'Provide old_text and new_text, or a non-empty edits array.';
+ }
+ const normalized = textEdit(args.old_text, args.new_text, args.replace_all);
+ return typeof normalized === 'string' ? normalized : [normalized];
+}
diff --git a/packages/api/src/agents/handlers.spec.ts b/packages/api/src/agents/handlers.spec.ts
index 74e006f684..22fdf7ef6d 100644
--- a/packages/api/src/agents/handlers.spec.ts
+++ b/packages/api/src/agents/handlers.spec.ts
@@ -4741,6 +4741,30 @@ describe('createToolExecuteHandler', () => {
);
});
+ it.each([[], '[]', null, {}, 'not json', [null]].map((edits) => [edits]))(
+ 'rejects invalid supplied edits %# without loading or writing the file',
+ async (edits) => {
+ const getSkillByName = jest.fn();
+ const saveSkillFileContent = jest.fn();
+ const handler = makeAuthoringHandler({ getSkillByName, saveSkillFileContent });
+ const [result] = await invokeHandler(handler, [
+ {
+ id: 'call_invalid_edit_batch',
+ name: 'edit_file',
+ args: {
+ path: 'skills/edit-skill/references/a.md',
+ edits,
+ old_text: 'original',
+ new_text: 'replacement',
+ },
+ },
+ ]);
+ expect(result.status).toBe('error');
+ expect(getSkillByName).not.toHaveBeenCalled();
+ expect(saveSkillFileContent).not.toHaveBeenCalled();
+ },
+ );
+
it('still rejects an unparseable edits string with the explicit error', async () => {
const saveSkillFileContent = jest.fn();
const handler = makeAuthoringHandler({
diff --git a/packages/api/src/agents/handlers.ts b/packages/api/src/agents/handlers.ts
index 78d6636f92..8c4132f644 100644
--- a/packages/api/src/agents/handlers.ts
+++ b/packages/api/src/agents/handlers.ts
@@ -58,6 +58,7 @@ import type { CodeExecutionContext } from './execution';
import type { TextContentFragment } from '~/protection';
import type { RunFileSession } from './files/session';
import type { ServerRequest } from '~/types';
+import type { TextEdit } from './edits';
import {
backgroundTaskRegistry,
runCheckBackgroundTask,
@@ -146,6 +147,7 @@ import { cleanCodeToolOutput } from './cleanup';
import { primeSkillFiles } from './skillFiles';
import { instrumentPtcToolMap } from './ptc';
import { markSandboxReady } from './prewarm';
+import { normalizeEditArgs } from './edits';
export interface ToolEndCallbackData {
/** The executed call's arguments. The stream-consumer tool-end path cannot
@@ -1048,13 +1050,6 @@ type ParsedSkillAuthoringPath = {
displayPath: string;
};
-type TextEdit = {
- old_text: string;
- new_text: string;
- /** Replaces every location instead of requiring exactly one. */
- replace_all?: boolean;
-};
-
type MatchedRange = { index: number; length: number };
type MatchStatus =
@@ -1645,73 +1640,6 @@ function getAuthorInfo(req: ServerRequest): {
};
}
-/* Models often stringify nested JSON (JSON-in-JSON) instead of passing a
- real array/object, which would otherwise fail validation and cost a retry
- round-trip. Parse a JSON string back to its value; leave non-strings and
- unparseable strings untouched so the explicit errors below still fire. */
-function coerceJsonValue(value: unknown): unknown {
- if (typeof value !== 'string') {
- return value;
- }
- try {
- return JSON.parse(value);
- } catch {
- return value;
- }
-}
-
-/** `replace_all` as a boolean, tolerating the stringified form some models send. */
-function normalizeReplaceAll(value: unknown): boolean | undefined | string {
- if (value === true || value === 'true') return true;
- if (value === undefined || value === null || value === false || value === 'false') {
- return undefined;
- }
- return 'replace_all must be true or false.';
-}
-
-function textEdit(oldText: string, newText: string, rawReplaceAll: unknown): TextEdit | string {
- if (oldText.length === 0) {
- return 'old_text cannot be empty.';
- }
- const replaceAll = normalizeReplaceAll(rawReplaceAll);
- if (typeof replaceAll === 'string') return replaceAll;
- return replaceAll
- ? { old_text: oldText, new_text: newText, replace_all: true }
- : { old_text: oldText, new_text: newText };
-}
-
-function normalizeEditArgs(args: {
- old_text?: unknown;
- new_text?: unknown;
- replace_all?: unknown;
- edits?: unknown;
-}): TextEdit[] | string {
- const coercedEdits = coerceJsonValue(args.edits);
- if (Array.isArray(coercedEdits) && coercedEdits.length > 0) {
- const edits: TextEdit[] = [];
- for (const rawEdit of coercedEdits) {
- const edit = coerceJsonValue(rawEdit);
- if (!edit || typeof edit !== 'object') {
- return 'Each edit must be an object with old_text and new_text.';
- }
- const entry = edit as { old_text?: unknown; new_text?: unknown; replace_all?: unknown };
- if (typeof entry.old_text !== 'string' || typeof entry.new_text !== 'string') {
- return 'Each edit requires string old_text and new_text.';
- }
- const normalized = textEdit(entry.old_text, entry.new_text, entry.replace_all);
- if (typeof normalized === 'string') return normalized;
- edits.push(normalized);
- }
- return edits;
- }
-
- if (typeof args.old_text !== 'string' || typeof args.new_text !== 'string') {
- return 'Provide old_text and new_text, or a non-empty edits array.';
- }
- const normalized = textEdit(args.old_text, args.new_text, args.replace_all);
- return typeof normalized === 'string' ? normalized : [normalized];
-}
-
/**
* Ranges a whitespace-tolerant strategy collects before it stops looking. An
* internal memory bound, not a policy: ambiguity only needs a second match, and
diff --git a/packages/api/src/agents/hitl/byom.ts b/packages/api/src/agents/hitl/byom.ts
index c4c25fa3a8..c349836454 100644
--- a/packages/api/src/agents/hitl/byom.ts
+++ b/packages/api/src/agents/hitl/byom.ts
@@ -137,6 +137,28 @@ export function markNativeCodeToolApprovalRequests(
};
}
+/** Scope native edit normalization to the executing agent, never a same-name external tool. */
+export function collectNativeEditFileAgentIds(
+ roots: readonly (CodeEnvironmentPolicyAgent | null | undefined)[],
+): Set<string> {
+ const agentIds = new Set<string>();
+ for (const agent of collectCodeEnvironmentPolicyAgents(roots)) {
+ if (!agent.id) continue;
+ let native = false;
+ let conflicting = false;
+ for (const definition of [
+ ...(agent.toolDefinitions ?? []),
+ ...(agent.toolRegistry?.values() ?? []),
+ ]) {
+ if (definition.name !== EDIT_FILE_TOOL_NAME) continue;
+ if (definition.toolType === 'builtin') native = true;
+ else conflicting = true;
+ }
+ if (native && !conflicting) agentIds.add(agent.id);
+ }
+ return agentIds;
+}
+
export class AttachedCodeEnvironmentApprovalError extends Error {
readonly code = 'BYOM_TOOL_APPROVAL_UNSUPPORTED';
diff --git a/packages/api/src/agents/hitl/edits.spec.ts b/packages/api/src/agents/hitl/edits.spec.ts
new file mode 100644
index 0000000000..592b9f28e7
--- /dev/null
+++ b/packages/api/src/agents/hitl/edits.spec.ts
@@ -0,0 +1,378 @@
+import { z } from 'zod';
+import { AIMessage } from '@langchain/core/messages';
+import { tool } from '@librechat/agents/langchain/tools';
+import { ToolNode, executeHooks } from '@librechat/agents';
+import {
+ Command,
+ END,
+ START,
+ MemorySaver,
+ StateGraph,
+ MessagesAnnotation,
+} from '@langchain/langgraph';
+import type { ToolExecuteBatchRequest } from '@librechat/agents';
+import type { Agents } from 'librechat-data-provider';
+import type { ToolApprovalHook } from './hooks';
+import { buildApprovalPreview } from '../../../../../client/src/components/Chat/approval/preview';
+import { collectNativeEditFileAgentIds } from './byom';
+import { buildHITLRunWiring } from './runtime';
+import { normalizeEditArgs } from '../edits';
+
+const nativeAgentIds = new Set(['native-agent']);
+const effectiveInput = {
+ path: 'workspace/example.ts',
+ edits: [{ old_text: 'original', new_text: 'replacement', replace_all: true }],
+};
+
+function evaluate(
+ wiring: NonNullable<ReturnType<typeof buildHITLRunWiring>>,
+ toolInput: Parameters<ToolApprovalHook>[0]['toolInput'],
+ executingAgentId = 'native-agent',
+) {
+ return executeHooks({
+ registry: wiring.hooks,
+ matchQuery: 'edit_file',
+ input: {
+ hook_event_name: 'PreToolUse',
+ runId: 'edit-run',
+ executingAgentId,
+ toolName: 'edit_file',
+ toolUseId: 'edit-call',
+ toolInput,
+ },
+ });
+}
+
+describe('native edit approval normalization', () => {
+ test.each([[], '[]', null, {}, 'not json', [null]].map((edits) => [edits]))(
+ 'denies malformed supplied edits %# before asking for approval',
+ async (edits) => {
+ const hook = jest.fn(async () => ({ decision: 'ask' as const }));
+ const wiring = buildHITLRunWiring({ enabled: true }, {}, [], [{ hook }], nativeAgentIds)!;
+ const result = await evaluate(wiring, {
+ path: effectiveInput.path,
+ edits,
+ old_text: 'original',
+ new_text: 'replacement',
+ });
+ expect(result.decision).toBe('deny');
+ expect(result.reason).toContain('edit');
+ expect(hook).not.toHaveBeenCalled();
+ expect(result.updatedInput).toBeUndefined();
+ },
+ );
+
+ test.each([
+ { old_text: 'original', new_text: 'replacement', replace_all: 'true' },
+ { edits: JSON.stringify(effectiveInput.edits) },
+ { edits: effectiveInput.edits.map((edit) => JSON.stringify(edit)) },
+ ])('offers the same canonical replacements execution consumes: %#', async (args) => {
+ const hook = jest.fn(async () => ({}));
+ const wiring = buildHITLRunWiring({ enabled: true }, {}, [], [{ hook }], nativeAgentIds)!;
+ const input = { path: effectiveInput.path, intent: 'Updating', ...args };
+ const result = await evaluate(wiring, input);
+ expect(result.decision).toBe('ask');
+ expect(result.updatedInput).toBeUndefined();
+ expect(input).toEqual({ ...effectiveInput, intent: 'Updating' });
+ expect(hook.mock.calls[0]).toEqual([
+ expect.objectContaining({ toolInput: { ...effectiveInput, intent: 'Updating' } }),
+ expect.anything(),
+ ]);
+ expect(normalizeEditArgs(input)).toEqual(effectiveInput.edits);
+ expect(input).not.toHaveProperty('old_text');
+ expect(input).not.toHaveProperty('replace_all');
+ });
+
+ test('normalizes hook rewrites and preserves last-writer precedence over abstaining hooks', async () => {
+ const wiring = buildHITLRunWiring(
+ { enabled: true },
+ {},
+ [],
+ [
+ {
+ hook: async () => ({
+ updatedInput: {
+ path: effectiveInput.path,
+ edits: JSON.stringify([{ old_text: 'rewritten', new_text: '' }]),
+ old_text: 'ignored',
+ new_text: 'ignored',
+ },
+ }),
+ },
+ { hook: async () => ({}) },
+ { hook: async () => ({}), matcher: '^unrelated$' },
+ ],
+ nativeAgentIds,
+ )!;
+ const result = await evaluate(wiring, effectiveInput);
+ expect(result.decision).toBe('ask');
+ expect(result.updatedInput).toEqual({
+ path: effectiveInput.path,
+ edits: [{ old_text: 'rewritten', new_text: '' }],
+ });
+ });
+
+ test('denies a malformed hook rewrite rather than displaying or executing a fallback', async () => {
+ const wiring = buildHITLRunWiring(
+ { enabled: true, mode: 'bypass' },
+ {},
+ [],
+ [{ hook: async () => ({ updatedInput: { ...effectiveInput, edits: [] } }) }],
+ nativeAgentIds,
+ )!;
+ expect((await evaluate(wiring, effectiveInput)).decision).toBe('deny');
+ });
+
+ test('leaves same-name external tools untouched', async () => {
+ const wiring = buildHITLRunWiring({ enabled: true }, {}, [], [], nativeAgentIds)!;
+ const result = await evaluate(
+ wiring,
+ { edits: [], arbitrary: 'external contract' },
+ 'external',
+ );
+ expect(result.decision).toBe('ask');
+ expect(result.updatedInput).toBeUndefined();
+ });
+
+ test('uses live provenance for lazily initialized native agents', async () => {
+ const ids = new Set<string>();
+ const wiring = buildHITLRunWiring({ enabled: true }, {}, [], [], ids)!;
+ ids.add('native-agent');
+ const input = { path: effectiveInput.path, old_text: 'original', new_text: 'replacement' };
+ expect((await evaluate(wiring, input)).updatedInput).toBeUndefined();
+ expect(input).toEqual({
+ path: effectiveInput.path,
+ edits: [{ old_text: 'original', new_text: 'replacement' }],
+ });
+ });
+});
+
+describe('collectNativeEditFileAgentIds', () => {
+ test('walks children and registries, but excludes per-agent name conflicts', () => {
+ expect(
+ collectNativeEditFileAgentIds([
+ {
+ id: 'native-agent',
+ toolDefinitions: [{ name: 'edit_file', toolType: 'builtin' }],
+ lazySubagentConfigs: [
+ {
+ id: 'child',
+ toolRegistry: new Map([['edit_file', { name: 'edit_file', toolType: 'builtin' }]]),
+ },
+ ],
+ },
+ {
+ id: 'external',
+ toolDefinitions: [{ name: 'edit_file', toolType: 'mcp' }],
+ },
+ {
+ id: 'conflict',
+ toolDefinitions: [{ name: 'edit_file', toolType: 'builtin' }],
+ toolRegistry: new Map([['edit_file', { name: 'edit_file', toolType: 'mcp' }]]),
+ },
+ ]),
+ ).toEqual(new Set(['native-agent', 'child']));
+ });
+});
+
+describe('native edit approval interrupt and resume', () => {
+ test('displays and executes the same canonical replacements after a real pause', async () => {
+ const captured: (typeof effectiveInput)[] = [];
+ const editTool = tool(
+ async (args) => {
+ captured.push(args);
+ return 'updated';
+ },
+ {
+ name: 'edit_file',
+ description: 'Native edit regression fixture',
+ schema: z.object({
+ path: z.string(),
+ edits: z.array(
+ z.object({
+ old_text: z.string(),
+ new_text: z.string(),
+ replace_all: z.boolean(),
+ }),
+ ),
+ }),
+ },
+ );
+ const wiring = buildHITLRunWiring({ enabled: true }, {}, [], [], nativeAgentIds)!;
+ const node = new ToolNode<typeof MessagesAnnotation.State>({
+ tools: [editTool],
+ hookRegistry: wiring.hooks,
+ humanInTheLoop: wiring.humanInTheLoop,
+ executingAgentId: 'native-agent',
+ toolCallStepIds: new Map([['edit-call', 'step-1']]),
+ });
+ const graph = new StateGraph(MessagesAnnotation)
+ .addNode('tools', node)
+ .addEdge(START, 'tools')
+ .addEdge('tools', END)
+ .compile({ checkpointer: new MemorySaver() });
+ const config = { configurable: { thread_id: 'edit-thread', run_id: 'edit-run' } };
+ await graph.invoke(
+ {
+ messages: [
+ new AIMessage({
+ content: '',
+ tool_calls: [
+ {
+ id: 'edit-call',
+ name: 'edit_file',
+ args: {
+ path: effectiveInput.path,
+ edits: JSON.stringify(effectiveInput.edits),
+ old_text: 'not approved',
+ new_text: 'not approved',
+ },
+ },
+ ],
+ }),
+ ],
+ },
+ config,
+ );
+ const snapshot = await graph.getState(config);
+ const payload = snapshot.tasks[0].interrupts[0].value as Agents.ToolApprovalInterruptPayload;
+ expect(payload.type).toBe('tool_approval');
+ expect(payload.action_requests[0].arguments).toEqual(effectiveInput);
+ expect(captured).toEqual([]);
+ const preview = buildApprovalPreview({
+ ...payload.action_requests[0],
+ source: 'librechat_code',
+ });
+ expect(JSON.parse(preview.body)).toEqual(effectiveInput.edits);
+ await graph.invoke(new Command({ resume: { 'edit-call': { type: 'approve' } } }), config);
+ expect(captured).toEqual([effectiveInput]);
+ expect(JSON.parse(preview.body)).toEqual(captured[0].edits);
+ });
+});
+
+describe('reviewed native edit replay', () => {
+ test.each([false, true])(
+ 'preserves a one-time hook rewrite after graph reconstruction, event mode: %s',
+ async (eventDrivenMode) => {
+ const captured: (typeof effectiveInput)[] = [];
+ const seen = new Set<string>();
+ const reviewedInput = {
+ ...effectiveInput,
+ edits: [{ ...effectiveInput.edits[0], new_text: 'sanitized' }],
+ };
+ const saver = new MemorySaver();
+ const editTool = tool(
+ async (args) => {
+ captured.push(args);
+ return 'updated';
+ },
+ {
+ name: 'edit_file',
+ description: 'Native edit replay fixture',
+ schema: z.object({
+ path: z.string(),
+ edits: z.array(
+ z.object({
+ old_text: z.string(),
+ new_text: z.string(),
+ replace_all: z.boolean(),
+ }),
+ ),
+ }),
+ },
+ );
+ const createGraph = () => {
+ const wiring = buildHITLRunWiring(
+ { enabled: true },
+ {},
+ [],
+ [
+ {
+ hook: async (input) => {
+ if (seen.has(input.toolUseId)) return {};
+ seen.add(input.toolUseId);
+ return { updatedInput: reviewedInput };
+ },
+ },
+ ],
+ nativeAgentIds,
+ )!;
+ return new StateGraph(MessagesAnnotation)
+ .addNode(
+ 'tools',
+ new ToolNode<typeof MessagesAnnotation.State>({
+ tools: [editTool],
+ eventDrivenMode,
+ executingAgentId: 'native-agent',
+ toolCallStepIds: new Map([['edit-call', 'step-1']]),
+ hookRegistry: wiring.hooks,
+ humanInTheLoop: wiring.humanInTheLoop,
+ }),
+ )
+ .addEdge(START, 'tools')
+ .addEdge('tools', END)
+ .compile({ checkpointer: saver });
+ };
+ const config = {
+ configurable: { thread_id: `reviewed-edit-${eventDrivenMode}`, run_id: 'edit-run' },
+ callbacks: [
+ {
+ handleCustomEvent: async (name: string, data: unknown) => {
+ if (name !== 'on_tool_execute') return;
+ const request = data as ToolExecuteBatchRequest;
+ captured.push(request.toolCalls[0].args as typeof effectiveInput);
+ request.resolve(
+ request.toolCalls.map((call) => ({
+ toolCallId: call.id,
+ status: 'success' as const,
+ content: 'updated',
+ })),
+ );
+ },
+ },
+ ],
+ };
+ const graph = createGraph();
+ await graph.invoke(
+ {
+ messages: [
+ new AIMessage({
+ content: '',
+ tool_calls: [
+ {
+ id: 'edit-call',
+ name: 'edit_file',
+ args: { ...effectiveInput },
+ },
+ ],
+ }),
+ ],
+ },
+ config,
+ );
+ const snapshot = await graph.getState(config);
+ const interrupted = snapshot.tasks[0].interrupts[0];
+ const payload = interrupted.value as Agents.ToolApprovalInterruptPayload;
+ expect(payload.action_requests[0].arguments).toEqual(reviewedInput);
+ expect(captured).toEqual([]);
+ const preview = buildApprovalPreview({
+ ...payload.action_requests[0],
+ source: 'librechat_code',
+ });
+ const rebuilt = createGraph();
+ await rebuilt.invoke(
+ new Command({ resume: { [interrupted.id!]: { 'edit-call': { type: 'approve' } } } }),
+ {
+ ...config,
+ configurable: {
+ ...config.configurable,
+ /** Mirrors the checkpoint-derived evidence that Run.resume supplies to ToolNode. */
+ __librechat_tool_approval_review: { interruptId: interrupted.id, payload },
+ },
+ },
+ );
+ expect(captured).toEqual([reviewedInput]);
+ expect(JSON.parse(preview.body)).toEqual(captured[0].edits);
+ },
+ );
+});
diff --git a/packages/api/src/agents/hitl/runtime.ts b/packages/api/src/agents/hitl/runtime.ts
index 3253f61f33..94795e2e85 100644
--- a/packages/api/src/agents/hitl/runtime.ts
+++ b/packages/api/src/agents/hitl/runtime.ts
@@ -4,10 +4,13 @@ import {
TOOL_APPROVAL_EXECUTION_SCOPE_CONFIG_KEY,
} from '@librechat/agents';
import type { TToolApprovalPolicy } from 'librechat-data-provider';
+import type { HookCallback } from '@librechat/agents';
import type { ResolvedToolApprovalHook, ToolApprovalHookContext } from './hooks';
import type { MCPToolAlias } from '~/tools/classification';
import { isHITLEnabled, mapToolApprovalPolicy } from './policy';
import { buildToolApprovalHooks } from './hooks';
+import { EDIT_FILE_TOOL_NAME } from '../tools';
+import { normalizeEditArgs } from '../edits';
/** Stable across resumes; the job epoch separates edits that reuse a response id. */
export function buildToolApprovalExecutionConfig(
@@ -58,11 +61,45 @@ export function buildHITLRunWiring(
context: ToolApprovalHookContext = {},
mcpToolAliases: readonly MCPToolAlias[] = [],
resolvedProgrammaticHooks?: readonly ResolvedToolApprovalHook[],
+ nativeEditFileAgentIds: ReadonlySet<string> = new Set(),
): HITLRunWiring | undefined {
if (!isHITLEnabled(policy)) {
return undefined;
}
+ const normalizeInput = (input: Parameters<HookCallback<'PreToolUse'>>[0]['toolInput']) => {
+ if (typeof input.path !== 'string' || input.path.length === 0) return 'path is required';
+ const edits = normalizeEditArgs(input);
+ if (typeof edits === 'string') return edits;
+ const normalized: typeof input = { ...input, edits };
+ delete normalized.old_text;
+ delete normalized.new_text;
+ delete normalized.replace_all;
+ return normalized;
+ };
+ const withNormalizedEdits =
+ (hook: HookCallback<'PreToolUse'>): HookCallback<'PreToolUse'> =>
+ async (input, signal) => {
+ if (
+ input.toolName !== EDIT_FILE_TOOL_NAME ||
+ input.executingAgentId == null ||
+ !nativeEditFileAgentIds.has(input.executingAgentId)
+ ) {
+ return hook(input, signal);
+ }
+ const normalized = normalizeInput(input.toolInput);
+ if (typeof normalized === 'string') return { decision: 'deny', reason: normalized };
+ /** A fresh updatedInput would supersede the checkpointed proposal on approval replay. */
+ Object.assign(input.toolInput, normalized);
+ delete input.toolInput.old_text;
+ delete input.toolInput.new_text;
+ delete input.toolInput.replace_all;
+ const result = await hook(input, signal);
+ if (result?.updatedInput == null) return result;
+ const updatedInput = normalizeInput(result.updatedInput);
+ if (typeof updatedInput === 'string') return { decision: 'deny', reason: updatedInput };
+ return { ...result, updatedInput };
+ };
const registry = new HookRegistry();
let activePolicy: TToolApprovalPolicy | undefined = policy;
const aliases = [...mcpToolAliases];
@@ -72,8 +109,9 @@ export function buildHITLRunWiring(
// Static config-driven policy (mode/allow/deny/ask) — the baseline.
registry.register('PreToolUse', {
hooks: [
- async (input, signal) =>
+ withNormalizedEdits(async (input, signal) =>
createToolPolicyHook(mapToolApprovalPolicy(activePolicy) ?? {})(input, signal),
+ ),
],
});
@@ -81,12 +119,12 @@ export function buildHITLRunWiring(
const programmaticHooks = resolvedProgrammaticHooks ?? buildToolApprovalHooks(context);
for (const { hook, matcher } of programmaticHooks) {
if (matcher == null) {
- registry.register('PreToolUse', { hooks: [hook] });
+ registry.register('PreToolUse', { hooks: [withNormalizedEdits(hook)] });
continue;
}
registry.register('PreToolUse', {
hooks: [
- async (input, signal) => {
+ withNormalizedEdits(async (input, signal) => {
let regex: RegExp;
try {
regex = new RegExp(matcher);
@@ -107,7 +145,7 @@ export function buildHITLRunWiring(
}
}
return {};
- },
+ }),
],
});
}
diff --git a/packages/api/src/agents/run.ts b/packages/api/src/agents/run.ts
index a420b80d3c..0d0a97864e 100644
--- a/packages/api/src/agents/run.ts
+++ b/packages/api/src/agents/run.ts
@@ -66,6 +66,7 @@ import type { RunFadingTiers } from './fading';
import type * as t from '~/types';
import {
assertAttachedCodeEnvironmentApprovalSupported,
+ collectNativeEditFileAgentIds,
collectAttachedCodeEnvironmentAgentIds,
collectAttachedCodeEnvironmentPolicySettings,
createAttachedCodeEnvironmentPolicyHook,
@@ -2712,6 +2713,7 @@ export async function createRun({
healToolApprovalPolicy(toolApprovalPolicy, mcpToolAliases),
ASK_USER_QUESTION_TOOL_NAME,
);
+ const nativeEditFileAgentIds = collectNativeEditFileAgentIds(agents);
const approvalWiring = buildHITLRunWiring(
// The ask tool is exempt from the approval prompt (unless explicitly
// listed by the admin) — approving the right to ask a question is a
@@ -2748,9 +2750,13 @@ export async function createRun({
]
: []),
],
+ nativeEditFileAgentIds,
);
const hitl = hitlCapable ? approvalWiring : undefined;
registerResolvedMCPToolAliases = (resolvedAgent) => {
+ for (const agentId of collectNativeEditFileAgentIds([resolvedAgent])) {
+ nativeEditFileAgentIds.add(agentId);
+ }
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;