Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: support bash tools in local system (#9676)

Arvin Xu39cdb2057e8b
diff --git a/apps/desktop/src/main/controllers/ShellCommandCtr.ts b/apps/desktop/src/main/controllers/ShellCommandCtr.ts
new file mode 100644
index 00000000000..288cf724a15
--- /dev/null
+++ b/apps/desktop/src/main/controllers/ShellCommandCtr.ts
@@ -0,0 +1,242 @@
+import {
+ GetCommandOutputParams,
+ GetCommandOutputResult,
+ KillCommandParams,
+ KillCommandResult,
+ RunCommandParams,
+ RunCommandResult,
+} from '@lobechat/electron-client-ipc';
+import { ChildProcess, spawn } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+
+import { createLogger } from '@/utils/logger';
+
+import { ControllerModule, ipcClientEvent } from './index';
+
+const logger = createLogger('controllers:ShellCommandCtr');
+
+interface ShellProcess {
+ lastReadStderr: number;
+ lastReadStdout: number;
+ process: ChildProcess;
+ stderr: string[];
+ stdout: string[];
+}
+
+export default class ShellCommandCtr extends ControllerModule {
+ // Shell process management
+ private shellProcesses = new Map<string, ShellProcess>();
+
+ @ipcClientEvent('runCommand')
+ async handleRunCommand({
+ command,
+ description,
+ run_in_background,
+ timeout = 120_000,
+ }: RunCommandParams): Promise<RunCommandResult> {
+ const logPrefix = `[runCommand: ${description || command.slice(0, 50)}]`;
+ logger.debug(`${logPrefix} Starting command execution`, {
+ background: run_in_background,
+ timeout,
+ });
+
+ // Validate timeout
+ const effectiveTimeout = Math.min(Math.max(timeout, 1000), 600_000);
+
+ // Cross-platform shell selection
+ const shellConfig =
+ process.platform === 'win32'
+ ? { args: ['/c', command], cmd: 'cmd.exe' }
+ : { args: ['-c', command], cmd: '/bin/sh' };
+
+ try {
+ if (run_in_background) {
+ // Background execution
+ const shellId = randomUUID();
+ const childProcess = spawn(shellConfig.cmd, shellConfig.args, {
+ env: process.env,
+ shell: false,
+ });
+
+ const shellProcess: ShellProcess = {
+ lastReadStderr: 0,
+ lastReadStdout: 0,
+ process: childProcess,
+ stderr: [],
+ stdout: [],
+ };
+
+ // Capture output
+ childProcess.stdout?.on('data', (data) => {
+ shellProcess.stdout.push(data.toString());
+ });
+
+ childProcess.stderr?.on('data', (data) => {
+ shellProcess.stderr.push(data.toString());
+ });
+
+ childProcess.on('exit', (code) => {
+ logger.debug(`${logPrefix} Background process exited`, { code, shellId });
+ });
+
+ this.shellProcesses.set(shellId, shellProcess);
+
+ logger.info(`${logPrefix} Started background execution`, { shellId });
+ return {
+ shell_id: shellId,
+ success: true,
+ };
+ } else {
+ // Synchronous execution with timeout
+ return new Promise((resolve) => {
+ const childProcess = spawn(shellConfig.cmd, shellConfig.args, {
+ env: process.env,
+ shell: false,
+ });
+
+ let stdout = '';
+ let stderr = '';
+ let killed = false;
+
+ const timeoutHandle = setTimeout(() => {
+ killed = true;
+ childProcess.kill();
+ resolve({
+ error: `Command timed out after ${effectiveTimeout}ms`,
+ stderr,
+ stdout,
+ success: false,
+ });
+ }, effectiveTimeout);
+
+ childProcess.stdout?.on('data', (data) => {
+ stdout += data.toString();
+ });
+
+ childProcess.stderr?.on('data', (data) => {
+ stderr += data.toString();
+ });
+
+ childProcess.on('exit', (code) => {
+ if (!killed) {
+ clearTimeout(timeoutHandle);
+ const success = code === 0;
+ logger.info(`${logPrefix} Command completed`, { code, success });
+ resolve({
+ exit_code: code || 0,
+ output: stdout + stderr,
+ stderr,
+ stdout,
+ success,
+ });
+ }
+ });
+
+ childProcess.on('error', (error) => {
+ clearTimeout(timeoutHandle);
+ logger.error(`${logPrefix} Command failed:`, error);
+ resolve({
+ error: error.message,
+ stderr,
+ stdout,
+ success: false,
+ });
+ });
+ });
+ }
+ } catch (error) {
+ logger.error(`${logPrefix} Failed to execute command:`, error);
+ return {
+ error: (error as Error).message,
+ success: false,
+ };
+ }
+ }
+
+ @ipcClientEvent('getCommandOutput')
+ async handleGetCommandOutput({
+ filter,
+ shell_id,
+ }: GetCommandOutputParams): Promise<GetCommandOutputResult> {
+ const logPrefix = `[getCommandOutput: ${shell_id}]`;
+ logger.debug(`${logPrefix} Retrieving output`);
+
+ const shellProcess = this.shellProcesses.get(shell_id);
+ if (!shellProcess) {
+ logger.error(`${logPrefix} Shell process not found`);
+ return {
+ error: `Shell ID ${shell_id} not found`,
+ output: '',
+ running: false,
+ stderr: '',
+ stdout: '',
+ success: false,
+ };
+ }
+
+ const { lastReadStderr, lastReadStdout, process: childProcess, stderr, stdout } = shellProcess;
+
+ // Get new output since last read
+ const newStdout = stdout.slice(lastReadStdout).join('');
+ const newStderr = stderr.slice(lastReadStderr).join('');
+ let output = newStdout + newStderr;
+
+ // Apply filter if provided
+ if (filter) {
+ try {
+ const regex = new RegExp(filter, 'gm');
+ const lines = output.split('\n');
+ output = lines.filter((line) => regex.test(line)).join('\n');
+ } catch (error) {
+ logger.error(`${logPrefix} Invalid filter regex:`, error);
+ }
+ }
+
+ // Update last read positions separately
+ shellProcess.lastReadStdout = stdout.length;
+ shellProcess.lastReadStderr = stderr.length;
+
+ const running = childProcess.exitCode === null;
+
+ logger.debug(`${logPrefix} Output retrieved`, {
+ outputLength: output.length,
+ running,
+ });
+
+ return {
+ output,
+ running,
+ stderr: newStderr,
+ stdout: newStdout,
+ success: true,
+ };
+ }
+
+ @ipcClientEvent('killCommand')
+ async handleKillCommand({ shell_id }: KillCommandParams): Promise<KillCommandResult> {
+ const logPrefix = `[killCommand: ${shell_id}]`;
+ logger.debug(`${logPrefix} Attempting to kill shell`);
+
+ const shellProcess = this.shellProcesses.get(shell_id);
+ if (!shellProcess) {
+ logger.error(`${logPrefix} Shell process not found`);
+ return {
+ error: `Shell ID ${shell_id} not found`,
+ success: false,
+ };
+ }
+
+ try {
+ shellProcess.process.kill();
+ this.shellProcesses.delete(shell_id);
+ logger.info(`${logPrefix} Shell killed successfully`);
+ return { success: true };
+ } catch (error) {
+ logger.error(`${logPrefix} Failed to kill shell:`, error);
+ return {
+ error: (error as Error).message,
+ success: false,
+ };
+ }
+ }
+}
diff --git a/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
new file mode 100644
index 00000000000..1d5e5e0f5f1
--- /dev/null
+++ b/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts
@@ -0,0 +1,499 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { App } from '@/core/App';
+
+import ShellCommandCtr from '../ShellCommandCtr';
+
+// Mock logger
+vi.mock('@/utils/logger', () => ({
+ createLogger: () => ({
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ }),
+}));
+
+// Mock child_process
+vi.mock('node:child_process', () => ({
+ spawn: vi.fn(),
+}));
+
+// Mock crypto
+vi.mock('node:crypto', () => ({
+ randomUUID: vi.fn(() => 'test-uuid-123'),
+}));
+
+const mockApp = {} as unknown as App;
+
+describe('ShellCommandCtr', () => {
+ let shellCommandCtr: ShellCommandCtr;
+ let mockSpawn: any;
+ let mockChildProcess: any;
+
+ beforeEach(async () => {
+ vi.clearAllMocks();
+
+ // Import mocks
+ const childProcessModule = await import('node:child_process');
+ mockSpawn = vi.mocked(childProcessModule.spawn);
+
+ // Create mock child process
+ mockChildProcess = {
+ stdout: {
+ on: vi.fn(),
+ },
+ stderr: {
+ on: vi.fn(),
+ },
+ on: vi.fn(),
+ kill: vi.fn(),
+ exitCode: null,
+ };
+
+ mockSpawn.mockReturnValue(mockChildProcess);
+
+ shellCommandCtr = new ShellCommandCtr(mockApp);
+ });
+
+ describe('handleRunCommand', () => {
+ describe('synchronous mode', () => {
+ it('should execute command successfully', async () => {
+ let exitCallback: (code: number) => void;
+ let stdoutCallback: (data: Buffer) => void;
+
+ mockChildProcess.on.mockImplementation((event: string, callback: any) => {
+ if (event === 'exit') {
+ exitCallback = callback;
+ // Simulate successful exit
+ setTimeout(() => exitCallback(0), 10);
+ }
+ return mockChildProcess;
+ });
+
+ mockChildProcess.stdout.on.mockImplementation((event: string, callback: any) => {
+ if (event === 'data') {
+ stdoutCallback = callback;
+ // Simulate output
+ setTimeout(() => stdoutCallback(Buffer.from('test output\n')), 5);
+ }
+ return mockChildProcess.stdout;
+ });
+
+ mockChildProcess.stderr.on.mockImplementation(() => mockChildProcess.stderr);
+
+ const result = await shellCommandCtr.handleRunCommand({
+ command: 'echo "test"',
+ description: 'test command',
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.stdout).toBe('test output\n');
+ expect(result.exit_code).toBe(0);
+ });
+
+ it('should handle command timeout', async () => {
+ mockChildProcess.on.mockImplementation(() => mockChildProcess);
+ mockChildProcess.stdout.on.mockImplementation(() => mockChildProcess.stdout);
+ mockChildProcess.stderr.on.mockImplementation(() => mockChildProcess.stderr);
+
+ const result = await shellCommandCtr.handleRunCommand({
+ command: 'sleep 10',
+ description: 'long running command',
+ timeout: 100,
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('timed out');
+ expect(mockChildProcess.kill).toHaveBeenCalled();
+ });
+
+ it('should handle command execution error', async () => {
+ let errorCallback: (error: Error) => void;
+
+ mockChildProcess.on.mockImplementation((event: string, callback: any) => {
+ if (event === 'error') {
+ errorCallback = callback;
+ setTimeout(() => errorCallback(new Error('Command not found')), 10);
+ }
+ return mockChildProcess;
+ });
+
+ mockChildProcess.stdout.on.mockImplementation(() => mockChildProcess.stdout);
+ mockChildProcess.stderr.on.mockImplementation(() => mockChildProcess.stderr);
+
+ const result = await shellCommandCtr.handleRunCommand({
+ command: 'invalid-command',
+ description: 'invalid command',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe('Command not found');
+ });
+
+ it('should handle non-zero exit code', async () => {
+ let exitCallback: (code: number) => void;
+
+ mockChildProcess.on.mockImplementation((event: string, callback: any) => {
+ if (event === 'exit') {
+ exitCallback = callback;
+ setTimeout(() => exitCallback(1), 10);
+ }
+ return mockChildProcess;
+ });
+
+ mockChildProcess.stdout.on.mockImplementation(() => mockChildProcess.stdout);
+ mockChildProcess.stderr.on.mockImplementation(() => mockChildProcess.stderr);
+
+ const result = await shellCommandCtr.handleRunCommand({
+ command: 'exit 1',
+ description: 'failing command',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.exit_code).toBe(1);
+ });
+
+ it('should capture stderr output', async () => {
+ let exitCallback: (code: number) => void;
+ let stderrCallback: (data: Buffer) => void;
+
+ mockChildProcess.on.mockImplementation((event: string, callback: any) => {
+ if (event === 'exit') {
+ exitCallback = callback;
+ setTimeout(() => exitCallback(1), 10);
+ }
+ return mockChildProcess;
+ });
+
+ mockChildProcess.stdout.on.mockImplementation(() => mockChildProcess.stdout);
+ mockChildProcess.stderr.on.mockImplementation((event: string, callback: any) => {
+ if (event === 'data') {
+ stderrCallback = callback;
+ setTimeout(() => stderrCallback(Buffer.from('error message\n')), 5);
+ }
+ return mockChildProcess.stderr;
+ });
+
+ const result = await shellCommandCtr.handleRunCommand({
+ command: 'command-with-error',
+ description: 'command with stderr',
+ });
+
+ expect(result.stderr).toBe('error message\n');
+ });
+
+ it('should enforce timeout limits', async () => {
+ mockChildProcess.on.mockImplementation(() => mockChildProcess);
+ mockChildProcess.stdout.on.mockImplementation(() => mockChildProcess.stdout);
+ mockChildProcess.stderr.on.mockImplementation(() => mockChildProcess.stderr);
+
+ // Test minimum timeout
+ const minResult = await shellCommandCtr.handleRunCommand({
+ command: 'sleep 5',
+ timeout: 500, // Below 1000ms minimum
+ });
+
+ expect(minResult.success).toBe(false);
+ expect(minResult.error).toContain('1000ms'); // Should use 1000ms minimum
+ });
+ });
+
+ describe('background mode', () => {
+ it('should start command in background', async () => {
+ mockChildProcess.on.mockImplementation(() => mockChildProcess);
+ mockChildProcess.stdout.on.mockImplementation(() => mockChildProcess.stdout);
+ mockChildProcess.stderr.on.mockImplementation(() => mockChildProcess.stderr);
+
+ const result = await shellCommandCtr.handleRunCommand({
+ command: 'long-running-task',
+ description: 'background task',
+ run_in_background: true,
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.shell_id).toBe('test-uuid-123');
+ });
+
+ it('should use correct shell on Windows', async () => {
+ const originalPlatform = process.platform;
+ Object.defineProperty(process, 'platform', { value: 'win32' });
+
+ mockChildProcess.on.mockImplementation(() => mockChildProcess);
+ mockChildProcess.stdout.on.mockImplementation(() => mockChildProcess.stdout);
+ mockChildProcess.stderr.on.mockImplementation(() => mockChildProcess.stderr);
+
+ await shellCommandCtr.handleRunCommand({
+ command: 'dir',
+ description: 'windows command',
+ run_in_background: true,
+ });
+
+ expect(mockSpawn).toHaveBeenCalledWith('cmd.exe', ['/c', 'dir'], expect.any(Object));
+
+ Object.defineProperty(process, 'platform', { value: originalPlatform });
+ });
+
+ it('should use correct shell on Unix', async () => {
+ const originalPlatform = process.platform;
+ Object.defineProperty(process, 'platform', { value: 'darwin' });
+
+ mockChildProcess.on.mockImplementation(() => mockChildProcess);
+ mockChildProcess.stdout.on.mockImplementation(() => mockChildProcess.stdout);
+ mockChildProcess.stderr.on.mockImplementation(() => mockChildProcess.stderr);
+
+ await shellCommandCtr.handleRunCommand({
+ command: 'ls',
+ description: 'unix command',
+ run_in_background: true,
+ });
+
+ expect(mockSpawn).toHaveBeenCalledWith('/bin/sh', ['-c', 'ls'], expect.any(Object));
+
+ Object.defineProperty(process, 'platform', { value: originalPlatform });
+ });
+ });
+ });
+
+ describe('handleGetCommandOutput', () => {
+ beforeEach(async () => {
+ mockChildProcess.on.mockImplementation(() => mockChildProcess);
+ mockChildProcess.stdout.on.mockImplementation((event: string, callback: any) => {
+ if (event === 'data') {
+ // Simulate some output
+ setTimeout(() => callback(Buffer.from('line 1\n')), 5);
+ setTimeout(() => callback(Buffer.from('line 2\n')), 10);
+ }
+ return mockChildProcess.stdout;
+ });
+ mockChildProcess.stderr.on.mockImplementation((event: string, callback: any) => {
+ if (event === 'data') {
+ setTimeout(() => callback(Buffer.from('error line\n')), 7);
+ }
+ return mockChildProcess.stderr;
+ });
+
+ // Start a background process first
+ await shellCommandCtr.handleRunCommand({
+ command: 'test-command',
+ run_in_background: true,
+ });
+ });
+
+ it('should retrieve command output', async () => {
+ // Wait for output to be captured
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ const result = await shellCommandCtr.handleGetCommandOutput({
+ shell_id: 'test-uuid-123',
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.stdout).toContain('line 1');
+ expect(result.stderr).toContain('error line');
+ });
+
+ it('should return error for non-existent shell_id', async () => {
+ const result = await shellCommandCtr.handleGetCommandOutput({
+ shell_id: 'non-existent-id',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('not found');
+ });
+
+ it('should filter output with regex', async () => {
+ // Wait for output to be captured
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ const result = await shellCommandCtr.handleGetCommandOutput({
+ shell_id: 'test-uuid-123',
+ filter: 'line 1',
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.output).toContain('line 1');
+ expect(result.output).not.toContain('line 2');
+ });
+
+ it('should only return new output since last read', async () => {
+ // Wait for initial output
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ // First read
+ const firstResult = await shellCommandCtr.handleGetCommandOutput({
+ shell_id: 'test-uuid-123',
+ });
+
+ expect(firstResult.stdout).toContain('line 1');
+
+ // Second read should return empty (no new output)
+ const secondResult = await shellCommandCtr.handleGetCommandOutput({
+ shell_id: 'test-uuid-123',
+ });
+
+ expect(secondResult.stdout).toBe('');
+ expect(secondResult.stderr).toBe('');
+ });
+
+ it('should handle invalid regex filter gracefully', async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ const result = await shellCommandCtr.handleGetCommandOutput({
+ shell_id: 'test-uuid-123',
+ filter: '[invalid(regex',
+ });
+
+ expect(result.success).toBe(true);
+ // Should return unfiltered output when filter is invalid
+ });
+
+ it('should report running status correctly', async () => {
+ mockChildProcess.exitCode = null;
+
+ const runningResult = await shellCommandCtr.handleGetCommandOutput({
+ shell_id: 'test-uuid-123',
+ });
+
+ expect(runningResult.running).toBe(true);
+
+ // Simulate process exit
+ mockChildProcess.exitCode = 0;
+
+ const exitedResult = await shellCommandCtr.handleGetCommandOutput({
+ shell_id: 'test-uuid-123',
+ });
+
+ expect(exitedResult.running).toBe(false);
+ });
+
+ it('should track stdout and stderr offsets separately when streaming output', async () => {
+ // Create a new background process with manual control over stdout/stderr
+ let stdoutCallback: (data: Buffer) => void;
+ let stderrCallback: (data: Buffer) => void;
+
+ mockChildProcess.stdout.on.mockImplementation((event: string, callback: any) => {
+ if (event === 'data') {
+ stdoutCallback = callback;
+ }
+ return mockChildProcess.stdout;
+ });
+
+ mockChildProcess.stderr.on.mockImplementation((event: string, callback: any) => {
+ if (event === 'data') {
+ stderrCallback = callback;
+ }
+ return mockChildProcess.stderr;
+ });
+
+ // Start a new background process
+ await shellCommandCtr.handleRunCommand({
+ command: 'test-interleaved',
+ run_in_background: true,
+ });
+
+ // Simulate stderr output first
+ stderrCallback(Buffer.from('error 1\n'));
+ await new Promise((resolve) => setTimeout(resolve, 5));
+
+ // First read - should get stderr
+ const firstRead = await shellCommandCtr.handleGetCommandOutput({
+ shell_id: 'test-uuid-123',
+ });
+ expect(firstRead.stderr).toBe('error 1\n');
+ expect(firstRead.stdout).toBe('');
+
+ // Simulate stdout output after stderr
+ stdoutCallback(Buffer.from('output 1\n'));
+ await new Promise((resolve) => setTimeout(resolve, 5));
+
+ // Second read - should get stdout without losing data
+ const secondRead = await shellCommandCtr.handleGetCommandOutput({
+ shell_id: 'test-uuid-123',
+ });
+ expect(secondRead.stdout).toBe('output 1\n');
+ expect(secondRead.stderr).toBe('');
+
+ // Simulate more stderr
+ stderrCallback(Buffer.from('error 2\n'));
+ await new Promise((resolve) => setTimeout(resolve, 5));
+
+ // Third read - should get new stderr
+ const thirdRead = await shellCommandCtr.handleGetCommandOutput({
+ shell_id: 'test-uuid-123',
+ });
+ expect(thirdRead.stderr).toBe('error 2\n');
+ expect(thirdRead.stdout).toBe('');
+
+ // Simulate more stdout
+ stdoutCallback(Buffer.from('output 2\n'));
+ await new Promise((resolve) => setTimeout(resolve, 5));
+
+ // Fourth read - should get new stdout
+ const fourthRead = await shellCommandCtr.handleGetCommandOutput({
+ shell_id: 'test-uuid-123',
+ });
+ expect(fourthRead.stdout).toBe('output 2\n');
+ expect(fourthRead.stderr).toBe('');
+ });
+ });
+
+ describe('handleKillCommand', () => {
+ beforeEach(async () => {
+ mockChildProcess.on.mockImplementation(() => mockChildProcess);
+ mockChildProcess.stdout.on.mockImplementation(() => mockChildProcess.stdout);
+ mockChildProcess.stderr.on.mockImplementation(() => mockChildProcess.stderr);
+
+ // Start a background process
+ await shellCommandCtr.handleRunCommand({
+ command: 'test-command',
+ run_in_background: true,
+ });
+ });
+
+ it('should kill command successfully', async () => {
+ const result = await shellCommandCtr.handleKillCommand({
+ shell_id: 'test-uuid-123',
+ });
+
+ expect(result.success).toBe(true);
+ expect(mockChildProcess.kill).toHaveBeenCalled();
+ });
+
+ it('should return error for non-existent shell_id', async () => {
+ const result = await shellCommandCtr.handleKillCommand({
+ shell_id: 'non-existent-id',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain('not found');
+ });
+
+ it('should remove process from map after killing', async () => {
+ await shellCommandCtr.handleKillCommand({
+ shell_id: 'test-uuid-123',
+ });
+
+ // Try to get output from killed process
+ const outputResult = await shellCommandCtr.handleGetCommandOutput({
+ shell_id: 'test-uuid-123',
+ });
+
+ expect(outputResult.success).toBe(false);
+ expect(outputResult.error).toContain('not found');
+ });
+
+ it('should handle kill error gracefully', async () => {
+ mockChildProcess.kill.mockImplementation(() => {
+ throw new Error('Kill failed');
+ });
+
+ const result = await shellCommandCtr.handleKillCommand({
+ shell_id: 'test-uuid-123',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe('Kill failed');
+ });
+ });
+});
diff --git a/locales/ar/chat.json b/locales/ar/chat.json
index 245d75737ab..53ea43c8136 100644
--- a/locales/ar/chat.json
+++ b/locales/ar/chat.json
@@ -369,6 +369,26 @@
"remained": "متبقي",
"used": "مستخدم"
},
+ "tool": {
+ "intervention": {
+ "approve": "الموافقة",
+ "approveAndRemember": "الموافقة والتذكر",
+ "approveOnce": "الموافقة لمرة واحدة فقط",
+ "mode": {
+ "allowList": "قائمة السماح",
+ "allowListDesc": "تنفيذ الأدوات المعتمدة فقط تلقائيًا",
+ "autoRun": "الموافقة التلقائية",
+ "autoRunDesc": "الموافقة تلقائيًا على تنفيذ جميع الأدوات",
+ "manual": "يدوي",
+ "manualDesc": "يتطلب الموافقة اليدوية في كل مرة يتم فيها الاستدعاء"
+ },
+ "reject": "رفض",
+ "rejectReasonPlaceholder": "إدخال سبب الرفض سيساعد الوكيل على الفهم وتحسين الإجراءات المستقبلية",
+ "rejectTitle": "رفض استدعاء الأداة هذه المرة",
+ "rejectedWithReason": "تم رفض استدعاء الأداة هذه المرة بشكل يدوي: {{reason}}",
+ "toolRejected": "تم رفض استدعاء الأداة هذه المرة بشكل يدوي"
+ }
+ },
"topic": {
"checkOpenNewTopic": "هل ترغب في فتح موضوع جديد؟",
"checkSaveCurrentMessages": "هل ترغب في حفظ الدردشة الحالية كموضوع؟",
diff --git a/locales/ar/common.json b/locales/ar/common.json
index a1790c9f237..a8e1e20dfcb 100644
--- a/locales/ar/common.json
+++ b/locales/ar/common.json
@@ -135,6 +135,7 @@
}
},
"close": "إغلاق",
+ "confirm": "تأكيد",
"contact": "اتصل بنا",
"copy": "نسخ",
"copyFail": "فشل في النسخ",
diff --git a/locales/ar/components.json b/locales/ar/components.json
index b30a1273d8a..606939fb1c8 100644
--- a/locales/ar/components.json
+++ b/locales/ar/components.json
@@ -106,6 +106,12 @@
"keyPlaceholder": "المفتاح",
"valuePlaceholder": "القيمة"
},
+ "LocalFile": {
+ "action": {
+ "open": "فتح",
+ "showInFolder": "عرض في المجلد"
+ }
+ },
"MaxTokenSlider": {
"unlimited": "غير محدود"
},
diff --git a/locales/ar/plugin.json b/locales/ar/plugin.json
index 17ac2f1ecd8..3c8d4afba3a 100644
--- a/locales/ar/plugin.json
+++ b/locales/ar/plugin.json
@@ -255,6 +255,7 @@
"moveLocalFiles": "نقل الملفات",
"readLocalFile": "قراءة محتوى الملف",
"renameLocalFile": "إعادة تسمية",
+ "runCommand": "تشغيل الأمر",
"searchLocalFiles": "بحث في الملفات",
"writeLocalFile": "كتابة في الملف"
},
diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.json
index 155914c157f..237fc19d0fd 100644
--- a/locales/bg-BG/chat.json
+++ b/locales/bg-BG/chat.json
@@ -369,6 +369,26 @@
"remained": "Оставащи",
"used": "Използвани"
},
+ "tool": {
+ "intervention": {
+ "approve": "Одобряване",
+ "approveAndRemember": "Одобряване и запомняне",
+ "approveOnce": "Одобряване само този път",
+ "mode": {
+ "allowList": "Бял списък",
+ "allowListDesc": "Автоматично се изпълняват само одобрените инструменти",
+ "autoRun": "Автоматично одобрение",
+ "autoRunDesc": "Автоматично одобряване на всички изпълнения на инструменти",
+ "manual": "Ръчно",
+ "manualDesc": "Необходимо е ръчно одобрение при всяко извикване"
+ },
+ "reject": "Отхвърляне",
+ "rejectReasonPlaceholder": "Въведете причина за отхвърляне, за да помогнете на агента да разбере и подобри бъдещите действия",
+ "rejectTitle": "Отхвърляне на това извикване на инструмент",
+ "rejectedWithReason": "Това извикване на инструмент беше умишлено отхвърлено: {{reason}}",
+ "toolRejected": "Това извикване на инструмент беше умишлено отхвърлено"
+ }
+ },
"topic": {
"checkOpenNewTopic": "Да се отвори ли нова тема?",
"checkSaveCurrentMessages": "Искате ли да запазите текущата сесия като тема?",
diff --git a/locales/bg-BG/common.json b/locales/bg-BG/common.json
index 3e3ce97c5db..559ebcbe706 100644
--- a/locales/bg-BG/common.json
+++ b/locales/bg-BG/common.json
@@ -135,6 +135,7 @@
}
},
"close": "Затвори",
+ "confirm": "Потвърди",
"contact": "Свържете се с нас",
"copy": "Копирай",
"copyFail": "Копирането не е успешно",
diff --git a/locales/bg-BG/components.json b/locales/bg-BG/components.json
index 4c0af01828b..767fcdaaec8 100644
--- a/locales/bg-BG/components.json
+++ b/locales/bg-BG/components.json
@@ -106,6 +106,12 @@
"keyPlaceholder": "Ключ",
"valuePlaceholder": "Стойност"
},
+ "LocalFile": {
+ "action": {
+ "open": "Отвори",
+ "showInFolder": "Показване в папката"
+ }
+ },
"MaxTokenSlider": {
"unlimited": "Неограничено"
},
diff --git a/locales/bg-BG/plugin.json b/locales/bg-BG/plugin.json
index b7821201243..4029a97be78 100644
--- a/locales/bg-BG/plugin.json
+++ b/locales/bg-BG/plugin.json
@@ -255,6 +255,7 @@
"moveLocalFiles": "Преместване на файлове",
"readLocalFile": "Четене на съдържание на файл",
"renameLocalFile": "Преименуване",
+ "runCommand": "Изпълни код",
"searchLocalFiles": "Търсене на файлове",
"writeLocalFile": "Запис в файл"
},
diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.json
index daefcfb5f2f..b3a7cd23767 100644
--- a/locales/de-DE/chat.json
+++ b/locales/de-DE/chat.json
@@ -369,6 +369,26 @@
"remained": "Verbleibend",
"used": "Verwendet"
},
+ "tool": {
+ "intervention": {
+ "approve": "Genehmigen",
+ "approveAndRemember": "Genehmigen und merken",
+ "approveOnce": "Nur dieses Mal genehmigen",
+ "mode": {
+ "allowList": "Positivliste",
+ "allowListDesc": "Nur automatisch genehmigte Tools ausführen",
+ "autoRun": "Automatisch genehmigen",
+ "autoRunDesc": "Alle Tool-Ausführungen automatisch genehmigen",
+ "manual": "Manuell",
+ "manualDesc": "Jede Ausführung muss manuell genehmigt werden"
+ },
+ "reject": "Ablehnen",
+ "rejectReasonPlaceholder": "Die Angabe eines Ablehnungsgrundes hilft dem Agenten, zukünftige Aktionen zu verbessern",
+ "rejectTitle": "Tool-Ausführung ablehnen",
+ "rejectedWithReason": "Die Tool-Ausführung wurde abgelehnt: {{reason}}",
+ "toolRejected": "Die Tool-Ausführung wurde abgelehnt"
+ }
+ },
"topic": {
"checkOpenNewTopic": "Soll ein neues Thema eröffnet werden?",
"checkSaveCurrentMessages": "Möchten Sie die aktuelle Konversation als Thema speichern?",
diff --git a/locales/de-DE/common.json b/locales/de-DE/common.json
index be7eb6dcc01..3e7ce7f8f85 100644
--- a/locales/de-DE/common.json
+++ b/locales/de-DE/common.json
@@ -135,6 +135,7 @@
}
},
"close": "Schließen",
+ "confirm": "Bestätigen",
"contact": "Kontakt",
"copy": "Kopieren",
"copyFail": "Kopieren fehlgeschlagen",
diff --git a/locales/de-DE/components.json b/locales/de-DE/components.json
index b50cdfda18c..e8f06fdf246 100644
--- a/locales/de-DE/components.json
+++ b/locales/de-DE/components.json
@@ -106,6 +106,12 @@
"keyPlaceholder": "Schlüssel",
"valuePlaceholder": "Wert"
},
+ "LocalFile": {
+ "action": {
+ "open": "Öffnen",
+ "showInFolder": "Im Ordner anzeigen"
+ }
+ },
"MaxTokenSlider": {
"unlimited": "Unbegrenzt"
},
diff --git a/locales/de-DE/plugin.json b/locales/de-DE/plugin.json
index 7fdfb6611c1..047013c0d8d 100644
--- a/locales/de-DE/plugin.json
+++ b/locales/de-DE/plugin.json
@@ -255,6 +255,7 @@
"moveLocalFiles": "Dateien verschieben",
"readLocalFile": "Dateiinhalt lesen",
"renameLocalFile": "Datei umbenennen",
+ "runCommand": "Befehl ausführen",
"searchLocalFiles": "Dateien suchen",
"writeLocalFile": "Datei schreiben"
},
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index ef6508620e6..82db0c3127e 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -369,6 +369,26 @@
"remained": "Remaining",
"used": "Used"
},
+ "tool": {
+ "intervention": {
+ "approve": "Approve",
+ "approveAndRemember": "Approve and Remember",
+ "approveOnce": "Approve This Time Only",
+ "mode": {
+ "allowList": "Allow List",
+ "allowListDesc": "Only automatically execute approved tools",
+ "autoRun": "Auto Approve",
+ "autoRunDesc": "Automatically approve all tool executions",
+ "manual": "Manual",
+ "manualDesc": "Manual approval required for each invocation"
+ },
+ "reject": "Reject",
+ "rejectReasonPlaceholder": "Providing a reason will help the Agent understand and improve future actions",
+ "rejectTitle": "Reject This Tool Invocation",
+ "rejectedWithReason": "This tool invocation was actively rejected: {{reason}}",
+ "toolRejected": "This tool invocation was actively rejected"
+ }
+ },
"topic": {
"checkOpenNewTopic": "Enable new topic?",
"checkSaveCurrentMessages": "Do you want to save the current conversation as a topic?",
diff --git a/locales/en-US/common.json b/locales/en-US/common.json
index 2ee8064f404..6209d0402ea 100644
--- a/locales/en-US/common.json
+++ b/locales/en-US/common.json
@@ -135,6 +135,7 @@
}
},
"close": "Close",
+ "confirm": "Confirm",
"contact": "Contact Us",
"copy": "Copy",
"copyFail": "Copy failed",
diff --git a/locales/en-US/components.json b/locales/en-US/components.json
index 1c35ec27abb..08b1c33780c 100644
--- a/locales/en-US/components.json
+++ b/locales/en-US/components.json
@@ -106,6 +106,12 @@
"keyPlaceholder": "Key",
"valuePlaceholder": "Value"
},
+ "LocalFile": {
+ "action": {
+ "open": "Open",
+ "showInFolder": "Show in Folder"
+ }
+ },
"MaxTokenSlider": {
"unlimited": "Unlimited"
},
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index 7c2bb9d4952..237d76fce56 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -255,6 +255,7 @@
"moveLocalFiles": "Move Files",
"readLocalFile": "Read File Content",
"renameLocalFile": "Rename",
+ "runCommand": "Run Code",
"searchLocalFiles": "Search Files",
"writeLocalFile": "Write File"
},
diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.json
index 529f8a2ab3f..e8e30c96ea7 100644
--- a/locales/es-ES/chat.json
+++ b/locales/es-ES/chat.json
@@ -369,6 +369,26 @@
"remained": "Restante",
"used": "Usado"
},
+ "tool": {
+ "intervention": {
+ "approve": "Aprobar",
+ "approveAndRemember": "Aprobar y recordar",
+ "approveOnce": "Aprobar solo esta vez",
+ "mode": {
+ "allowList": "Lista blanca",
+ "allowListDesc": "Ejecutar automáticamente solo las herramientas aprobadas",
+ "autoRun": "Aprobación automática",
+ "autoRunDesc": "Aprobar automáticamente la ejecución de todas las herramientas",
+ "manual": "Manual",
+ "manualDesc": "Se requiere aprobación manual para cada ejecución"
+ },
+ "reject": "Rechazar",
+ "rejectReasonPlaceholder": "Ingresar una razón ayudará al agente a comprender y mejorar futuras acciones",
+ "rejectTitle": "Rechazar esta ejecución de herramienta",
+ "rejectedWithReason": "Esta ejecución de herramienta fue rechazada: {{reason}}",
+ "toolRejected": "Esta ejecución de herramienta fue rechazada"
+ }
+ },
"topic": {
"checkOpenNewTopic": "¿Abrir un nuevo tema?",
"checkSaveCurrentMessages": "¿Desea guardar la conversación actual como tema?",
diff --git a/locales/es-ES/common.json b/locales/es-ES/common.json
index e9d1bbc7a97..5e948a02234 100644
--- a/locales/es-ES/common.json
+++ b/locales/es-ES/common.json
@@ -135,6 +135,7 @@
}
},
"close": "Cerrar",
+ "confirm": "Confirmar",
"contact": "Contacto",
"copy": "Copiar",
"copyFail": "Fallo al copiar",
diff --git a/locales/es-ES/components.json b/locales/es-ES/components.json
index f679f77318c..1336ae71d12 100644
--- a/locales/es-ES/components.json
+++ b/locales/es-ES/components.json
@@ -106,6 +106,12 @@
"keyPlaceholder": "Clave",
"valuePlaceholder": "Valor"
},
+ "LocalFile": {
+ "action": {
+ "open": "Abrir",
+ "showInFolder": "Mostrar en la carpeta"
+ }
+ },
"MaxTokenSlider": {
"unlimited": "Sin límite"
},
diff --git a/locales/es-ES/plugin.json b/locales/es-ES/plugin.json
index 6592337fd27..28051c63f90 100644
--- a/locales/es-ES/plugin.json
+++ b/locales/es-ES/plugin.json
@@ -255,6 +255,7 @@
"moveLocalFiles": "Mover archivos",
"readLocalFile": "Leer contenido del archivo",
"renameLocalFile": "Renombrar",
+ "runCommand": "Ejecutar código",
"searchLocalFiles": "Buscar archivos",
"writeLocalFile": "Escribir archivo"
},
diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.json
index cf4eb157a07..6f64ef3bfd7 100644
--- a/locales/fa-IR/chat.json
+++ b/locales/fa-IR/chat.json
@@ -369,6 +369,26 @@
"remained": "باقی‌مانده",
"used": "استفاده شده"
},
+ "tool": {
+ "intervention": {
+ "approve": "تأیید",
+ "approveAndRemember": "تأیید و به خاطر سپردن",
+ "approveOnce": "تأیید فقط برای این بار",
+ "mode": {
+ "allowList": "فهرست مجاز",
+ "allowListDesc": "فقط ابزارهای تأییدشده به‌صورت خودکار اجرا می‌شوند",
+ "autoRun": "تأیید خودکار",
+ "autoRunDesc": "تأیید خودکار اجرای همه ابزارها",
+ "manual": "دستی",
+ "manualDesc": "نیاز به تأیید دستی برای هر بار فراخوانی"
+ },
+ "reject": "رد کردن",
+ "rejectReasonPlaceholder": "وارد کردن دلیل رد به Agent کمک می‌کند تا اقدامات بعدی را بهینه کند",
+ "rejectTitle": "رد این فراخوانی ابزار",
+ "rejectedWithReason": "این فراخوانی ابزار با دلیل زیر رد شد:{{reason}}",
+ "toolRejected": "این فراخوانی ابزار به‌صورت دستی رد شد"
+ }
+ },
"topic": {
"checkOpenNewTopic": "آیا مایل به باز کردن موضوع جدید هستید؟",
"checkSaveCurrentMessages": "آیا مایل به ذخیره مکالمه فعلی به عنوان موضوع هستید؟",
diff --git a/locales/fa-IR/common.json b/locales/fa-IR/common.json
index 32b347d3707..4fbf75b5ea6 100644
--- a/locales/fa-IR/common.json
+++ b/locales/fa-IR/common.json
@@ -135,6 +135,7 @@
}
},
"close": "بستن",
+ "confirm": "تأیید",
"contact": "تماس با ما",
"copy": "کپی",
"copyFail": "کپی ناموفق بود",
diff --git a/locales/fa-IR/components.json b/locales/fa-IR/components.json
index 8c938b2f223..da5b614b1c3 100644
--- a/locales/fa-IR/components.json
+++ b/locales/fa-IR/components.json
@@ -106,6 +106,12 @@
"keyPlaceholder": "کلید",
"valuePlaceholder": "مقدار"
},
+ "LocalFile": {
+ "action": {
+ "open": "باز کردن",
+ "showInFolder": "نمایش در پوشه"
+ }
+ },
"MaxTokenSlider": {
"unlimited": "نامحدود"
},
diff --git a/locales/fa-IR/plugin.json b/locales/fa-IR/plugin.json
index ee6c2b048f7..8d3d194ab43 100644
--- a/locales/fa-IR/plugin.json
+++ b/locales/fa-IR/plugin.json
@@ -255,6 +255,7 @@
"moveLocalFiles": "جابجایی فایل‌ها",
"readLocalFile": "خواندن محتوای فایل",
"renameLocalFile": "تغییر نام",
+ "runCommand": "اجرای کد",
"searchLocalFiles": "جستجوی فایل‌ها",
"writeLocalFile": "نوشتن در فایل"
},
diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.json
index 1f2f31ab79e..1737381ff4b 100644
--- a/locales/fr-FR/chat.json
+++ b/locales/fr-FR/chat.json
@@ -369,6 +369,26 @@
"remained": "Restant",
"used": "Utilisé"
},
+ "tool": {
+ "intervention": {
+ "approve": "Approuver",
+ "approveAndRemember": "Approuver et mémoriser",
+ "approveOnce": "Approuver une seule fois",
+ "mode": {
+ "allowList": "Liste blanche",
+ "allowListDesc": "Exécuter automatiquement uniquement les outils approuvés",
+ "autoRun": "Exécution automatique",
+ "autoRunDesc": "Approuver automatiquement l'exécution de tous les outils",
+ "manual": "Manuel",
+ "manualDesc": "Chaque appel nécessite une approbation manuelle"
+ },
+ "reject": "Rejeter",
+ "rejectReasonPlaceholder": "Saisir une raison de rejet aidera l'agent à comprendre et à améliorer ses actions futures",
+ "rejectTitle": "Rejeter cet appel d'outil",
+ "rejectedWithReason": "Cet appel d'outil a été rejeté volontairement : {{reason}}",
+ "toolRejected": "Cet appel d'outil a été rejeté volontairement"
+ }
+ },
"topic": {
"checkOpenNewTopic": "Voulez-vous ouvrir un nouveau sujet ?",
"checkSaveCurrentMessages": "Voulez-vous enregistrer la conversation actuelle en tant que sujet ?",
diff --git a/locales/fr-FR/common.json b/locales/fr-FR/common.json
index e60c42e7cbe..ee32cba923f 100644
--- a/locales/fr-FR/common.json
+++ b/locales/fr-FR/common.json
@@ -135,6 +135,7 @@
}
},
"close": "Fermer",
+ "confirm": "Confirmer",
"contact": "Nous contacter",
"copy": "Copier",
"copyFail": "Échec de la copie",
diff --git a/locales/fr-FR/components.json b/locales/fr-FR/components.json
index e1895cb3366..6ed5144427c 100644
--- a/locales/fr-FR/components.json
+++ b/locales/fr-FR/components.json
@@ -106,6 +106,12 @@
"keyPlaceholder": "Clé",
"valuePlaceholder": "Valeur"
},
+ "LocalFile": {
+ "action": {
+ "open": "Ouvrir",
+ "showInFolder": "Afficher dans le dossier"
+ }
+ },
"MaxTokenSlider": {
"unlimited": "Illimité"
},
diff --git a/locales/fr-FR/plugin.json b/locales/fr-FR/plugin.json
index 77cfb00efe2..3a8aec7a480 100644
--- a/locales/fr-FR/plugin.json
+++ b/locales/fr-FR/plugin.json
@@ -255,6 +255,7 @@
"moveLocalFiles": "Déplacer les fichiers",
"readLocalFile": "Lire le contenu du fichier",
"renameLocalFile": "Renommer",
+ "runCommand": "Exécuter le code",
"searchLocalFiles": "Rechercher des fichiers",
"writeLocalFile": "Écrire dans un fichier"
},
diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.json
index 7a5a56f2ea9..2127409b6c1 100644
--- a/locales/it-IT/chat.json
+++ b/locales/it-IT/chat.json
@@ -369,6 +369,26 @@
"remained": "Rimasti",
"used": "Utilizzati"
},
+ "tool": {
+ "intervention": {
+ "approve": "Approva",
+ "approveAndRemember": "Approva e ricorda",
+ "approveOnce": "Approva solo questa volta",
+ "mode": {
+ "allowList": "Lista consentiti",
+ "allowListDesc": "Esegui automaticamente solo gli strumenti approvati",
+ "autoRun": "Approvazione automatica",
+ "autoRunDesc": "Approva automaticamente l'esecuzione di tutti gli strumenti",
+ "manual": "Manuale",
+ "manualDesc": "Richiede approvazione manuale per ogni utilizzo"
+ },
+ "reject": "Rifiuta",
+ "rejectReasonPlaceholder": "Inserire il motivo del rifiuto aiuterà l'agente a comprendere e ottimizzare le azioni future",
+ "rejectTitle": "Rifiuta questa esecuzione dello strumento",
+ "rejectedWithReason": "Questa esecuzione dello strumento è stata rifiutata: {{reason}}",
+ "toolRejected": "Questa esecuzione dello strumento è stata rifiutata"
+ }
+ },
"topic": {
"checkOpenNewTopic": "Abilitare un nuovo argomento?",
"checkSaveCurrentMessages": "Vuoi salvare la conversazione attuale come argomento?",
diff --git a/locales/it-IT/common.json b/locales/it-IT/common.json
index 01d5947a8b5..b77039fd467 100644
--- a/locales/it-IT/common.json
+++ b/locales/it-IT/common.json
@@ -135,6 +135,7 @@
}
},
"close": "Chiudi",
+ "confirm": "Conferma",
"contact": "Contattaci",
"copy": "Copia",
"copyFail": "Copia non riuscita",
diff --git a/locales/it-IT/components.json b/locales/it-IT/components.json
index 66681245995..aa370fcbad2 100644
--- a/locales/it-IT/components.json
+++ b/locales/it-IT/components.json
@@ -106,6 +106,12 @@
"keyPlaceholder": "Chiave",
"valuePlaceholder": "Valore"
},
+ "LocalFile": {
+ "action": {
+ "open": "Apri",
+ "showInFolder": "Mostra nella cartella"
+ }
+ },
"MaxTokenSlider": {
"unlimited": "Illimitato"
},
diff --git a/locales/it-IT/plugin.json b/locales/it-IT/plugin.json
index c2397985348..44e2c144fc9 100644
--- a/locales/it-IT/plugin.json
+++ b/locales/it-IT/plugin.json
@@ -255,6 +255,7 @@
"moveLocalFiles": "Sposta file",
"readLocalFile": "Leggi contenuto file",
"renameLocalFile": "Rinomina",
+ "runCommand": "Esegui codice",
"searchLocalFiles": "Cerca file",
"writeLocalFile": "Scrivi file"
},
diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.json
index cb58f809305..da173ccbc82 100644
--- a/locales/ja-JP/chat.json
+++ b/locales/ja-JP/chat.json
@@ -369,6 +369,26 @@
"remained": "残り",
"used": "使用済み"
},
+ "tool": {
+ "intervention": {
+ "approve": "承認",
+ "approveAndRemember": "承認して記憶する",
+ "approveOnce": "今回のみ承認",
+ "mode": {
+ "allowList": "ホワイトリスト",
+ "allowListDesc": "承認されたツールのみ自動実行されます",
+ "autoRun": "自動承認",
+ "autoRunDesc": "すべてのツール実行を自動的に承認します",
+ "manual": "手動",
+ "manualDesc": "毎回の呼び出しに手動承認が必要です"
+ },
+ "reject": "拒否",
+ "rejectReasonPlaceholder": "拒否理由を入力すると、エージェントが理解し今後の行動を最適化するのに役立ちます",
+ "rejectTitle": "今回のツール呼び出しを拒否",
+ "rejectedWithReason": "今回のツール呼び出しは次の理由で拒否されました:{{reason}}",
+ "toolRejected": "今回のツール呼び出しは拒否されました"
+ }
+ },
"topic": {
"checkOpenNewTopic": "新しいトピックを開始しますか?",
"checkSaveCurrentMessages": "現在の会話をトピックとして保存しますか?",
diff --git a/locales/ja-JP/common.json b/locales/ja-JP/common.json
index 8428af48f3f..0f6f14e5aad 100644
--- a/locales/ja-JP/common.json
+++ b/locales/ja-JP/common.json
@@ -135,6 +135,7 @@
}
},
"close": "閉じる",
+ "confirm": "確認",
"contact": "お問い合わせ",
"copy": "コピー",
"copyFail": "コピーに失敗しました",
diff --git a/locales/ja-JP/components.json b/locales/ja-JP/components.json
index 9882aa84249..6e0d3d059b4 100644
--- a/locales/ja-JP/components.json
+++ b/locales/ja-JP/components.json
@@ -106,6 +106,12 @@
"keyPlaceholder": "キー",
"valuePlaceholder": "値"
},
+ "LocalFile": {
+ "action": {
+ "open": "開く",
+ "showInFolder": "フォルダーで表示"
+ }
+ },
"MaxTokenSlider": {
"unlimited": "無制限"
},
diff --git a/locales/ja-JP/plugin.json b/locales/ja-JP/plugin.json
index 2b3d3b2d01e..d962cc2fd19 100644
--- a/locales/ja-JP/plugin.json
+++ b/locales/ja-JP/plugin.json
@@ -255,6 +255,7 @@
"moveLocalFiles": "ファイルを移動",
"readLocalFile": "ファイル内容を読み込み",
"renameLocalFile": "ファイル名を変更",
+ "runCommand": "コードを実行",
"searchLocalFiles": "ファイルを検索",
"writeLocalFile": "ファイルに書き込み"
},
diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.json
index a482ec1d0f7..c91b52198c3 100644
--- a/locales/ko-KR/chat.json
+++ b/locales/ko-KR/chat.json
@@ -369,6 +369,26 @@
"remained": "남음",
"used": "사용됨"
},
+ "tool": {
+ "intervention": {
+ "approve": "승인",
+ "approveAndRemember": "승인 및 기억하기",
+ "approveOnce": "이번만 승인",
+ "mode": {
+ "allowList": "허용 목록",
+ "allowListDesc": "승인된 도구만 자동 실행",
+ "autoRun": "자동 승인",
+ "autoRunDesc": "모든 도구 실행 자동 승인",
+ "manual": "수동",
+ "manualDesc": "매번 호출 시 수동 승인 필요"
+ },
+ "reject": "거부",
+ "rejectReasonPlaceholder": "거부 사유를 입력하면 에이전트가 이해하고 이후 행동을 최적화하는 데 도움이 됩니다",
+ "rejectTitle": "이번 도구 호출 거부",
+ "rejectedWithReason": "이번 도구 호출이 다음 사유로 거부됨: {{reason}}",
+ "toolRejected": "이번 도구 호출이 거부되었습니다"
+ }
+ },
"topic": {
"checkOpenNewTopic": "새 주제를 열까요?",
"checkSaveCurrentMessages": "현재 대화를 주제로 저장하시겠습니까?",
diff --git a/locales/ko-KR/common.json b/locales/ko-KR/common.json
index 2dfcbe3c16b..4b95306cebc 100644
--- a/locales/ko-KR/common.json
+++ b/locales/ko-KR/common.json
@@ -135,6 +135,7 @@
}
},
"close": "닫기",
+ "confirm": "확인",
"contact": "문의하기",
"copy": "복사",
"copyFail": "복사 실패",
diff --git a/locales/ko-KR/components.json b/locales/ko-KR/components.json
index a27b6a991ea..c60f9c5a549 100644
--- a/locales/ko-KR/components.json
+++ b/locales/ko-KR/components.json
@@ -106,6 +106,12 @@
"keyPlaceholder": "키",
"valuePlaceholder": "값"
},
+ "LocalFile": {
+ "action": {
+ "open": "열기",
+ "showInFolder": "폴더에서 보기"
+ }
+ },
"MaxTokenSlider": {
"unlimited": "제한 없음"
},
diff --git a/locales/ko-KR/plugin.json b/locales/ko-KR/plugin.json
index a60453dc8d2..44396ea49a2 100644
--- a/locales/ko-KR/plugin.json
+++ b/locales/ko-KR/plugin.json
@@ -255,6 +255,7 @@
"moveLocalFiles": "파일 이동",
"readLocalFile": "파일 내용 읽기",
"renameLocalFile": "파일 이름 변경",
+ "runCommand": "코드 실행",
"searchLocalFiles": "파일 검색",
"writeLocalFile": "파일 쓰기"
},
diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.json
index 418aeb29c86..a06415f0d2f 100644
--- a/locales/nl-NL/chat.json
+++ b/locales/nl-NL/chat.json
@@ -369,6 +369,26 @@
"remained": "Resterend",
"used": "Gebruikt"
},
+ "tool": {
+ "intervention": {
+ "approve": "Goedkeuren",
+ "approveAndRemember": "Goedkeuren en onthouden",
+ "approveOnce": "Alleen deze keer goedkeuren",
+ "mode": {
+ "allowList": "Toegestane lijst",
+ "allowListDesc": "Voer alleen automatisch goedgekeurde tools uit",
+ "autoRun": "Automatisch goedkeuren",
+ "autoRunDesc": "Keur automatisch alle tooluitvoeringen goed",
+ "manual": "Handmatig",
+ "manualDesc": "Handmatige goedkeuring vereist bij elke oproep"
+ },
+ "reject": "Weigeren",
+ "rejectReasonPlaceholder": "Het opgeven van een reden helpt de agent om toekomstige acties te verbeteren",
+ "rejectTitle": "Huidige tooloproep weigeren",
+ "rejectedWithReason": "Deze tooloproep is geweigerd met reden: {{reason}}",
+ "toolRejected": "Deze tooloproep is geweigerd"
+ }
+ },
"topic": {
"checkOpenNewTopic": "Is het openen van een nieuw onderwerp ingeschakeld?",
"checkSaveCurrentMessages": "Wil je het huidige gesprek opslaan als onderwerp?",
diff --git a/locales/nl-NL/common.json b/locales/nl-NL/common.json
index c24aa1d17c7..769e25c0a60 100644
--- a/locales/nl-NL/common.json
+++ b/locales/nl-NL/common.json
@@ -135,6 +135,7 @@
}
},
"close": "Sluiten",
+ "confirm": "Bevestigen",
"contact": "Contacteer ons",
"copy": "Kopiëren",
"copyFail": "Kopiëren mislukt",
diff --git a/locales/nl-NL/components.json b/locales/nl-NL/components.json
index ffe319cfeb6..227c5d99d60 100644
--- a/locales/nl-NL/components.json
+++ b/locales/nl-NL/components.json
@@ -106,6 +106,12 @@
"keyPlaceholder": "Sleutel",
"valuePlaceholder": "Waarde"
},
+ "LocalFile": {
+ "action": {
+ "open": "Openen",
+ "showInFolder": "In map weergeven"
+ }
+ },
"MaxTokenSlider": {
"unlimited": "Onbeperkt"
},
diff --git a/locales/nl-NL/plugin.json b/locales/nl-NL/plugin.json
index 9ae6b93c5f8..1a94e71ca63 100644
--- a/locales/nl-NL/plugin.json
+++ b/locales/nl-NL/plugin.json
@@ -255,6 +255,7 @@
"moveLocalFiles": "Bestanden verplaatsen",
"readLocalFile": "Bestandsinhoud lezen",
"renameLocalFile": "Naam wijzigen",
+ "runCommand": "Code uitvoeren",
"searchLocalFiles": "Bestanden zoeken",
"writeLocalFile": "Bestand schrijven"
},
diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.json
index 3a862f0a680..73af524f416 100644
--- a/locales/pl-PL/chat.json
+++ b/locales/pl-PL/chat.json
@@ -369,6 +369,26 @@
"remained": "Pozostało",
"used": "Użyte"
},
+ "tool": {
+ "intervention": {
+ "approve": "Zatwierdź",
+ "approveAndRemember": "Zatwierdź i zapamiętaj",
+ "approveOnce": "Zatwierdź tylko tym razem",
+ "mode": {
+ "allowList": "Lista dozwolonych",
+ "allowListDesc": "Automatycznie wykonuj tylko zatwierdzone narzędzia",
+ "autoRun": "Automatyczne zatwierdzanie",
+ "autoRunDesc": "Automatycznie zatwierdzaj wszystkie wykonania narzędzi",
+ "manual": "Ręcznie",
+ "manualDesc": "Każde wywołanie wymaga ręcznego zatwierdzenia"
+ },
+ "reject": "Odrzuć",
+ "rejectReasonPlaceholder": "Wprowadzenie powodu odrzucenia pomoże Agentowi zrozumieć i zoptymalizować przyszłe działania",
+ "rejectTitle": "Odrzuć to wywołanie narzędzia",
+ "rejectedWithReason": "To wywołanie narzędzia zostało odrzucone: {{reason}}",
+ "toolRejected": "To wywołanie narzędzia zostało odrzucone"
+ }
+ },
"topic": {
"checkOpenNewTopic": "Czy otworzyć nowy temat?",
"checkSaveCurrentMessages": "Czy zapisać bieżącą rozmowę jako temat?",
diff --git a/locales/pl-PL/common.json b/locales/pl-PL/common.json
index cc76190f8e0..a71bf90140c 100644
--- a/locales/pl-PL/common.json
+++ b/locales/pl-PL/common.json
@@ -135,6 +135,7 @@
}
},
"close": "Zamknij",
+ "confirm": "Potwierdź",
"contact": "Skontaktuj się z nami",
"copy": "Kopiuj",
"copyFail": "Nie udało się skopiować",
diff --git a/locales/pl-PL/components.json b/locales/pl-PL/components.json
index ed969449e83..f8c1d8ca2f8 100644
--- a/locales/pl-PL/components.json
+++ b/locales/pl-PL/components.json
@@ -106,6 +106,12 @@
"keyPlaceholder": "Klucz",
"valuePlaceholder": "Wartość"
},
+ "LocalFile": {
+ "action": {
+ "open": "Otwórz",
+ "showInFolder": "Pokaż w folderze"
+ }
+ },
"MaxTokenSlider": {
"unlimited": "Bez ograniczeń"
},
diff --git a/locales/pl-PL/plugin.json b/locales/pl-PL/plugin.json
index c9231f0874f..0ffa383b8a3 100644
--- a/locales/pl-PL/plugin.json
+++ b/locales/pl-PL/plugin.json
@@ -255,6 +255,7 @@
"moveLocalFiles": "Przenieś pliki",
"readLocalFile": "Odczytaj zawartość pliku",
"renameLocalFile": "Zmień nazwę",
+ "runCommand": "Wykonaj kod",
"searchLocalFiles": "Wyszukaj pliki",
"writeLocalFile": "Zapisz do pliku"
},
diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.json
index 485d744669b..1dcd90785ca 100644
--- a/locales/pt-BR/chat.json
+++ b/locales/pt-BR/chat.json
@@ -369,6 +369,26 @@
"remained": "Restante",
"used": "Usado"
},
+ "tool": {
+ "intervention": {
+ "approve": "Aprovar",
+ "approveAndRemember": "Aprovar e lembrar",
+ "approveOnce": "Aprovar apenas desta vez",
+ "mode": {
+ "allowList": "Lista de permissões",
+ "allowListDesc": "Executar automaticamente apenas as ferramentas aprovadas",
+ "autoRun": "Aprovação automática",
+ "autoRunDesc": "Aprovar automaticamente a execução de todas as ferramentas",
+ "manual": "Manual",
+ "manualDesc": "Requer aprovação manual a cada chamada"
+ },
+ "reject": "Rejeitar",
+ "rejectReasonPlaceholder": "Inserir o motivo da rejeição ajudará o Agente a entender e melhorar ações futuras",
+ "rejectTitle": "Rejeitar esta chamada de ferramenta",
+ "rejectedWithReason": "Esta chamada de ferramenta foi rejeitada: {{reason}}",
+ "toolRejected": "Esta chamada de ferramenta foi rejeitada"
+ }
+ },
"topic": {
"checkOpenNewTopic": "Deseja abrir um novo tópico?",
"checkSaveCurrentMessages": "Salvar a conversa atual como tópico?",
diff --git a/locales/pt-BR/common.json b/locales/pt-BR/common.json
index 5a9df266e78..bab01de7dfb 100644
--- a/locales/pt-BR/common.json
+++ b/locales/pt-BR/common.json
@@ -135,6 +135,7 @@
}
},
"close": "Fechar",
+ "confirm": "Confirmar",
"contact": "Entre em contato",
"copy": "Copiar",
"copyFail": "Falha ao copiar",
diff --git a/locales/pt-BR/components.json b/locales/pt-BR/components.json
index f0308798c4f..8ff34293d97 100644
--- a/locales/pt-BR/components.json
+++ b/locales/pt-BR/components.json
@@ -106,6 +106,12 @@
"keyPlaceholder": "Chave",
"valuePlaceholder": "Valor"
},
+ "LocalFile": {
+ "action": {
+ "open": "Abrir",
+ "showInFolder": "Mostrar na pasta"
+ }
+ },
"MaxTokenSlider": {
"unlimited": "Ilimitado"
},
diff --git a/locales/pt-BR/plugin.json b/locales/pt-BR/plugin.json
index 5fe76ff5299..b383070e45f 100644
--- a/locales/pt-BR/plugin.json
+++ b/locales/pt-BR/plugin.json
@@ -255,6 +255,7 @@
"moveLocalFiles": "Mover arquivos",
"readLocalFile": "Ler conteúdo do arquivo",
"renameLocalFile": "Renomear",
+ "runCommand": "Executar código",
"searchLocalFiles": "Pesquisar arquivos",
"writeLocalFile": "Escrever arquivo"
},
diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.json
index 50b24cda673..63c7a90d718 100644
--- a/locales/ru-RU/chat.json
+++ b/locales/ru-RU/chat.json
@@ -369,6 +369,26 @@
"remained": "Осталось",
"used": "Использовано"
},
+ "tool": {
+ "intervention": {
+ "approve": "Одобрить",
+ "approveAndRemember": "Одобрить и запомнить",
+ "approveOnce": "Одобрить только один раз",
+ "mode": {
+ "allowList": "Белый список",
+ "allowListDesc": "Автоматически выполнять только одобренные инструменты",
+ "autoRun": "Автоматическое одобрение",
+ "autoRunDesc": "Автоматически одобрять выполнение всех инструментов",
+ "manual": "Вручную",
+ "manualDesc": "Каждый вызов требует ручного одобрения"
+ },
+ "reject": "Отклонить",
+ "rejectReasonPlaceholder": "Указание причины отклонения поможет агенту лучше понять и улучшить последующие действия",
+ "rejectTitle": "Отклонить вызов инструмента",
+ "rejectedWithReason": "Вызов инструмента был отклонён по следующей причине: {{reason}}",
+ "toolRejected": "Вызов инструмента был отклонён"
+ }
+ },
"topic": {
"checkOpenNewTopic": "Открыть новую тему?",
"checkSaveCurrentMessages": "Сохранить текущий разговор как тему?",
diff --git a/locales/ru-RU/common.json b/locales/ru-RU/common.json
index 99e824857fb..09157b56386 100644
--- a/locales/ru-RU/common.json
+++ b/locales/ru-RU/common.json
@@ -135,6 +135,7 @@
}
},
"close": "Закрыть",
+ "confirm": "Подтвердить",
"contact": "Свяжитесь с нами",
"copy": "Копировать",
"copyFail": "Не удалось скопировать",
diff --git a/locales/ru-RU/components.json b/locales/ru-RU/components.json
index ae1797337d7..186822a232f 100644
--- a/locales/ru-RU/components.json
+++ b/locales/ru-RU/components.json
@@ -106,6 +106,12 @@
"keyPlaceholder": "Ключ",
"valuePlaceholder": "Значение"
},
+ "LocalFile": {
+ "action": {
+ "open": "Открыть",
+ "showInFolder": "Показать в папке"
+ }
+ },
"MaxTokenSlider": {
"unlimited": "Без ограничений"
},
diff --git a/locales/ru-RU/plugin.json b/locales/ru-RU/plugin.json
index 5faf7fdd7a6..c2df3e7dd84 100644
--- a/locales/ru-RU/plugin.json
+++ b/locales/ru-RU/plugin.json
@@ -255,6 +255,7 @@
"moveLocalFiles": "Перемещение файлов",
"readLocalFile": "Чтение содержимого файла",
"renameLocalFile": "Переименование",
+ "runCommand": "Выполнить код",
"searchLocalFiles": "Поиск файлов",
"writeLocalFile": "Запись в файл"
},
diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.json
index ff05c2e9bac..c93b136c10f 100644
--- a/locales/tr-TR/chat.json
+++ b/locales/tr-TR/chat.json
@@ -369,6 +369,26 @@
"remained": "Kalan",
"used": "Kullanılan"
},
+ "tool": {
+ "intervention": {
+ "approve": "Onayla",
+ "approveAndRemember": "Onayla ve Hatırla",
+ "approveOnce": "Sadece Bu Sefer Onayla",
+ "mode": {
+ "allowList": "Beyaz Liste",
+ "allowListDesc": "Yalnızca onaylanmış araçlar otomatik olarak çalıştırılır",
+ "autoRun": "Otomatik Onay",
+ "autoRunDesc": "Tüm araçların çalıştırılmasını otomatik olarak onayla",
+ "manual": "Manuel",
+ "manualDesc": "Her çağrı için manuel onay gerekir"
+ },
+ "reject": "Reddet",
+ "rejectReasonPlaceholder": "Reddetme nedenini girmek, Agent'ın anlamasına ve sonraki eylemleri iyileştirmesine yardımcı olur",
+ "rejectTitle": "Bu Araç Çağrısını Reddet",
+ "rejectedWithReason": "Bu araç çağrısı şu nedenle reddedildi: {{reason}}",
+ "toolRejected": "Bu araç çağrısı kullanıcı tarafından reddedildi"
+ }
+ },
"topic": {
"checkOpenNewTopic": "Yeni bir konu açılsın mı?",
"checkSaveCurrentMessages": "Mevcut sohbeti konu olarak kaydetmek istiyor musunuz?",
diff --git a/locales/tr-TR/common.json b/locales/tr-TR/common.json
index a9e3c038ec5..ba3b2b398da 100644
--- a/locales/tr-TR/common.json
+++ b/locales/tr-TR/common.json
@@ -135,6 +135,7 @@
}
},
"close": "Kapat",
+ "confirm": "Onayla",
"contact": "Bize Ulaşın",
"copy": "Kopyala",
"copyFail": "Kopyalama başarısız oldu",
diff --git a/locales/tr-TR/components.json b/locales/tr-TR/components.json
index e1810e3fbd9..b6634e5047a 100644
--- a/locales/tr-TR/components.json
+++ b/locales/tr-TR/components.json
@@ -106,6 +106,12 @@
"keyPlaceholder": "Anahtar",
"valuePlaceholder": "Değer"
},
+ "LocalFile": {
+ "action": {
+ "open": "Aç",
+ "showInFolder": "Klasörde Göster"
+ }
+ },
"MaxTokenSlider": {
"unlimited": "Sınırsız"
},
diff --git a/locales/tr-TR/plugin.json b/locales/tr-TR/plugin.json
index 79e13557326..1da85586a2a 100644
--- a/locales/tr-TR/plugin.json
+++ b/locales/tr-TR/plugin.json
@@ -255,6 +255,7 @@
"moveLocalFiles": "Dosya taşı",
"readLocalFile": "Dosya içeriğini oku",
"renameLocalFile": "Dosya adını değiştir",
+ "runCommand": "Komutu Çalıştır",
"searchLocalFiles": "Dosya ara",
"writeLocalFile": "Dosyaya yaz"
},
diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.json
index 63f98ebf3a8..68225865bc6 100644
--- a/locales/vi-VN/chat.json
+++ b/locales/vi-VN/chat.json
@@ -369,6 +369,26 @@
"remained": "Còn lại",
"used": "Đã sử dụng"
},
+ "tool": {
+ "intervention": {
+ "approve": "Phê duyệt",
+ "approveAndRemember": "Phê duyệt và ghi nhớ",
+ "approveOnce": "Chỉ phê duyệt lần này",
+ "mode": {
+ "allowList": "Danh sách cho phép",
+ "allowListDesc": "Chỉ tự động thực thi các công cụ đã được phê duyệt",
+ "autoRun": "Tự động phê duyệt",
+ "autoRunDesc": "Tự động phê duyệt tất cả các công cụ thực thi",
+ "manual": "Thủ công",
+ "manualDesc": "Mỗi lần gọi đều cần phê duyệt thủ công"
+ },
+ "reject": "Từ chối",
+ "rejectReasonPlaceholder": "Nhập lý do từ chối sẽ giúp Agent hiểu và cải thiện hành động sau này",
+ "rejectTitle": "Từ chối lần gọi công cụ này",
+ "rejectedWithReason": "Lần gọi công cụ này đã bị từ chối: {{reason}}",
+ "toolRejected": "Lần gọi công cụ này đã bị từ chối"
+ }
+ },
"topic": {
"checkOpenNewTopic": "Có muốn mở chủ đề mới không?",
"checkSaveCurrentMessages": "Bạn có muốn lưu cuộc trò chuyện hiện tại thành chủ đề không?",
diff --git a/locales/vi-VN/common.json b/locales/vi-VN/common.json
index 78b4b582e1a..3b69ec63527 100644
--- a/locales/vi-VN/common.json
+++ b/locales/vi-VN/common.json
@@ -135,6 +135,7 @@
}
},
"close": "Đóng",
+ "confirm": "Xác nhận",
"contact": "Liên hệ chúng tôi",
"copy": "Sao chép",
"copyFail": "Sao chép thất bại",
diff --git a/locales/vi-VN/components.json b/locales/vi-VN/components.json
index f65218b308a..dcda0b036c2 100644
--- a/locales/vi-VN/components.json
+++ b/locales/vi-VN/components.json
@@ -106,6 +106,12 @@
"keyPlaceholder": "Khóa",
"valuePlaceholder": "Giá trị"
},
+ "LocalFile": {
+ "action": {
+ "open": "Mở",
+ "showInFolder": "Hiển thị trong thư mục"
+ }
+ },
"MaxTokenSlider": {
"unlimited": "Không giới hạn"
},
diff --git a/locales/vi-VN/plugin.json b/locales/vi-VN/plugin.json
index d09fd23978c..7f30ae835f3 100644
--- a/locales/vi-VN/plugin.json
+++ b/locales/vi-VN/plugin.json
@@ -255,6 +255,7 @@
"moveLocalFiles": "Di chuyển tệp",
"readLocalFile": "Đọc nội dung tệp",
"renameLocalFile": "Đổi tên",
+ "runCommand": "Chạy mã",
"searchLocalFiles": "Tìm kiếm tệp",
"writeLocalFile": "Ghi tệp"
},
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 8d6b37b8d62..c0d76fed6b1 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -369,6 +369,26 @@
"remained": "剩余",
"used": "使用"
},
+ "tool": {
+ "intervention": {
+ "approve": "批准",
+ "approveAndRemember": "批准并记住",
+ "approveOnce": "仅本次批准",
+ "mode": {
+ "allowList": "白名单",
+ "allowListDesc": "仅自动执行已批准的工具",
+ "autoRun": "自动批准",
+ "autoRunDesc": "自动批准所有工具执行",
+ "manual": "手动",
+ "manualDesc": "每次调用都需要手动批准"
+ },
+ "reject": "拒绝",
+ "rejectReasonPlaceholder": "输入拒绝原因将帮助 Agent 理解并优化后续行动",
+ "rejectTitle": "拒绝本次工具调用",
+ "rejectedWithReason": "本次工具调用被主动拒绝:{{reason}}",
+ "toolRejected": "本次工具调用被主动拒绝"
+ }
+ },
"topic": {
"checkOpenNewTopic": "是否开启新话题?",
"checkSaveCurrentMessages": "是否保存当前会话为话题?",
diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.json
index cf7b2fe2abb..1f55cd09910 100644
--- a/locales/zh-CN/common.json
+++ b/locales/zh-CN/common.json
@@ -135,6 +135,7 @@
}
},
"close": "关闭",
+ "confirm": "确认",
"contact": "联系我们",
"copy": "复制",
"copyFail": "复制失败",
diff --git a/locales/zh-CN/components.json b/locales/zh-CN/components.json
index f05fcb9709f..0eb5a118f45 100644
--- a/locales/zh-CN/components.json
+++ b/locales/zh-CN/components.json
@@ -106,6 +106,12 @@
"keyPlaceholder": "键",
"valuePlaceholder": "值"
},
+ "LocalFile": {
+ "action": {
+ "open": "打开",
+ "showInFolder": "在文件夹中显示"
+ }
+ },
"MaxTokenSlider": {
"unlimited": "无限制"
},
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index bbe005eb452..8dd720613d3 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -255,6 +255,7 @@
"moveLocalFiles": "移动文件",
"readLocalFile": "读取文件内容",
"renameLocalFile": "重命名",
+ "runCommand": "执行代码",
"searchLocalFiles": "搜索文件",
"writeLocalFile": "写入文件"
},
diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.json
index cf825b48e05..0a299d75cc7 100644
--- a/locales/zh-TW/chat.json
+++ b/locales/zh-TW/chat.json
@@ -369,6 +369,26 @@
"remained": "剩餘",
"used": "使用"
},
+ "tool": {
+ "intervention": {
+ "approve": "批准",
+ "approveAndRemember": "批准並記住",
+ "approveOnce": "僅本次批准",
+ "mode": {
+ "allowList": "白名單",
+ "allowListDesc": "僅自動執行已批准的工具",
+ "autoRun": "自動批准",
+ "autoRunDesc": "自動批准所有工具執行",
+ "manual": "手動",
+ "manualDesc": "每次調用都需要手動批准"
+ },
+ "reject": "拒絕",
+ "rejectReasonPlaceholder": "輸入拒絕原因將幫助 Agent 理解並優化後續行動",
+ "rejectTitle": "拒絕本次工具調用",
+ "rejectedWithReason": "本次工具調用被主動拒絕:{{reason}}",
+ "toolRejected": "本次工具調用被主動拒絕"
+ }
+ },
"topic": {
"checkOpenNewTopic": "是否開啟新主題?",
"checkSaveCurrentMessages": "是否將當前對話保存為話題?",
diff --git a/locales/zh-TW/common.json b/locales/zh-TW/common.json
index c3b459877e0..1f0835705b6 100644
--- a/locales/zh-TW/common.json
+++ b/locales/zh-TW/common.json
@@ -135,6 +135,7 @@
}
},
"close": "關閉",
+ "confirm": "確認",
"contact": "聯繫我們",
"copy": "複製",
"copyFail": "複製失敗",
diff --git a/locales/zh-TW/components.json b/locales/zh-TW/components.json
index 849eed80fe9..7c4db5eb270 100644
--- a/locales/zh-TW/components.json
+++ b/locales/zh-TW/components.json
@@ -106,6 +106,12 @@
"keyPlaceholder": "鍵",
"valuePlaceholder": "值"
},
+ "LocalFile": {
+ "action": {
+ "open": "開啟",
+ "showInFolder": "在資料夾中顯示"
+ }
+ },
"MaxTokenSlider": {
"unlimited": "無限制"
},
diff --git a/locales/zh-TW/plugin.json b/locales/zh-TW/plugin.json
index bf1f15cf46b..4787058e98c 100644
--- a/locales/zh-TW/plugin.json
+++ b/locales/zh-TW/plugin.json
@@ -255,6 +255,7 @@
"moveLocalFiles": "移動檔案",
"readLocalFile": "讀取檔案內容",
"renameLocalFile": "重新命名",
+ "runCommand": "執行程式碼",
"searchLocalFiles": "搜尋檔案",
"writeLocalFile": "寫入檔案"
},
diff --git a/packages/agent-runtime/src/core/InterventionChecker.ts b/packages/agent-runtime/src/core/InterventionChecker.ts
index 0cfb62ddd3d..224120ab876 100644
--- a/packages/agent-runtime/src/core/InterventionChecker.ts
+++ b/packages/agent-runtime/src/core/InterventionChecker.ts
@@ -35,7 +35,7 @@ export class InterventionChecker {
}
// No rule matched - default to require for safety
- return 'require';
+ return 'required';
}
/**
diff --git a/packages/agent-runtime/src/core/__tests__/InterventionChecker.test.ts b/packages/agent-runtime/src/core/__tests__/InterventionChecker.test.ts
index a71b6a86446..959d5d85a79 100644
--- a/packages/agent-runtime/src/core/__tests__/InterventionChecker.test.ts
+++ b/packages/agent-runtime/src/core/__tests__/InterventionChecker.test.ts
@@ -12,16 +12,16 @@ describe('InterventionChecker', () => {
it('should return the policy when config is a simple string', () => {
expect(InterventionChecker.shouldIntervene({ config: 'never', toolArgs: {} })).toBe('never');
- expect(InterventionChecker.shouldIntervene({ config: 'require', toolArgs: {} })).toBe(
- 'require',
+ expect(InterventionChecker.shouldIntervene({ config: 'required', toolArgs: {} })).toBe(
+ 'required',
);
});
it('should match rules in order and return first match', () => {
const config: HumanInterventionConfig = [
{ match: { command: 'ls:*' }, policy: 'never' },
- { match: { command: 'git commit:*' }, policy: 'require' },
- { policy: 'require' }, // Default rule
+ { match: { command: 'git commit:*' }, policy: 'required' },
+ { policy: 'required' }, // Default rule
];
expect(InterventionChecker.shouldIntervene({ config, toolArgs: { command: 'ls:' } })).toBe(
@@ -29,10 +29,10 @@ describe('InterventionChecker', () => {
);
expect(
InterventionChecker.shouldIntervene({ config, toolArgs: { command: 'git commit:' } }),
- ).toBe('require');
+ ).toBe('required');
expect(
InterventionChecker.shouldIntervene({ config, toolArgs: { command: 'rm -rf /' } }),
- ).toBe('require');
+ ).toBe('required');
});
it('should return require as default when no rule matches', () => {
@@ -42,7 +42,7 @@ describe('InterventionChecker', () => {
config,
toolArgs: { command: 'rm -rf /' },
});
- expect(result).toBe('require');
+ expect(result).toBe('required');
});
it('should handle multiple parameter matching', () => {
@@ -54,7 +54,7 @@ describe('InterventionChecker', () => {
},
policy: 'never',
},
- { policy: 'require' },
+ { policy: 'required' },
];
// Both match
@@ -77,20 +77,20 @@ describe('InterventionChecker', () => {
path: '/tmp/file.ts',
},
}),
- ).toBe('require');
+ ).toBe('required');
});
it('should handle default rule without match', () => {
const config: HumanInterventionConfig = [
{ match: { command: 'ls:*' }, policy: 'never' },
- { policy: 'require' }, // Default rule
+ { policy: 'required' }, // Default rule
];
const result = InterventionChecker.shouldIntervene({
config,
toolArgs: { command: 'anything' },
});
- expect(result).toBe('require');
+ expect(result).toBe('required');
});
});
@@ -222,10 +222,10 @@ describe('InterventionChecker', () => {
it('should handle Bash tool scenario', () => {
const config: HumanInterventionConfig = [
{ match: { command: 'ls:*' }, policy: 'never' },
- { match: { command: 'git add:*' }, policy: 'require' },
- { match: { command: 'git commit:*' }, policy: 'require' },
- { match: { command: 'rm:*' }, policy: 'require' },
- { policy: 'require' },
+ { match: { command: 'git add:*' }, policy: 'required' },
+ { match: { command: 'git commit:*' }, policy: 'required' },
+ { match: { command: 'rm:*' }, policy: 'required' },
+ { policy: 'required' },
];
// Safe commands - never
@@ -236,24 +236,24 @@ describe('InterventionChecker', () => {
// Git commands - require
expect(
InterventionChecker.shouldIntervene({ config, toolArgs: { command: 'git add:.' } }),
- ).toBe('require');
+ ).toBe('required');
expect(
InterventionChecker.shouldIntervene({ config, toolArgs: { command: 'git commit:-m' } }),
- ).toBe('require');
+ ).toBe('required');
// Dangerous commands - require
expect(InterventionChecker.shouldIntervene({ config, toolArgs: { command: 'rm:-rf' } })).toBe(
- 'require',
+ 'required',
);
expect(
InterventionChecker.shouldIntervene({ config, toolArgs: { command: 'npm install' } }),
- ).toBe('require');
+ ).toBe('required');
});
it('should handle LocalSystem tool scenario', () => {
const config: HumanInterventionConfig = [
{ match: { path: '/Users/project/*' }, policy: 'never' },
- { policy: 'require' },
+ { policy: 'required' },
];
// Project directory - never
@@ -267,15 +267,15 @@ describe('InterventionChecker', () => {
// Outside project - require
expect(
InterventionChecker.shouldIntervene({ config, toolArgs: { path: '/tmp/file.ts' } }),
- ).toBe('require');
+ ).toBe('required');
});
it('should handle Web Browsing tool with simple policy', () => {
- const config: HumanInterventionConfig = 'require';
+ const config: HumanInterventionConfig = 'required';
expect(
InterventionChecker.shouldIntervene({ config, toolArgs: { url: 'https://example.com' } }),
- ).toBe('require');
+ ).toBe('required');
});
});
});
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index 1496488ee9e..4018d393031 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -1,5 +1,5 @@
/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
-import { ChatToolPayload } from '@/types/message';
+import { ChatToolPayload, UserInterventionConfig } from '@lobechat/types';
import type { Cost, CostLimit, Usage } from './usage';
@@ -17,6 +17,12 @@ export interface AgentState {
tools?: any[];
systemRole?: string;
toolManifestMap: Record<string, any>;
+
+ /**
+ * User's global intervention configuration
+ * Controls how tools requiring approval are handled
+ */
+ userInterventionConfig?: UserInterventionConfig;
// --- Execution Tracking ---
/**
* Number of execution steps in this session.
diff --git a/packages/const/src/settings/tool.ts b/packages/const/src/settings/tool.ts
index 1f6bd08bb2c..68791b132b9 100644
--- a/packages/const/src/settings/tool.ts
+++ b/packages/const/src/settings/tool.ts
@@ -1,5 +1 @@
-export const DEFAULT_TOOL_CONFIG = {
- dalle: {
- autoGenerate: false,
- },
-};
+export const DEFAULT_TOOL_CONFIG = {};
diff --git a/packages/file-loaders/src/loaders/docx/index.ts b/packages/file-loaders/src/loaders/docx/index.ts
index a5b1fb6a649..84a96c6c931 100644
--- a/packages/file-loaders/src/loaders/docx/index.ts
+++ b/packages/file-loaders/src/loaders/docx/index.ts
@@ -1,6 +1,6 @@
import debug from 'debug';
-import fs from 'node:fs/promises';
import mammoth from 'mammoth';
+import fs from 'node:fs/promises';
import type { DocumentPage, FileLoaderInterface } from '../../types';
diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.ts
index 5d74beb7519..4e52c68c5de 100644
--- a/packages/types/src/tool/builtin.ts
+++ b/packages/types/src/tool/builtin.ts
@@ -151,3 +151,12 @@ export interface BuiltinServerRuntimeOutput {
state?: any;
success: boolean;
}
+
+export interface BuiltinInterventionProps<Arguments = any> {
+ apiName?: string;
+ args: Arguments;
+ identifier?: string;
+ messageId: string;
+}
+
+export type BuiltinIntervention = (props: BuiltinInterventionProps) => ReactNode;
diff --git a/packages/types/src/tool/intervention.ts b/packages/types/src/tool/intervention.ts
index 67860e630a8..1896e72b358 100644
--- a/packages/types/src/tool/intervention.ts
+++ b/packages/types/src/tool/intervention.ts
@@ -5,9 +5,9 @@ import { z } from 'zod';
*/
export type HumanInterventionPolicy =
| 'never' // Never intervene, auto-execute
- | 'require'; // Always require intervention
+ | 'required'; // Always require intervention
-export const HumanInterventionPolicySchema = z.enum(['never', 'require']);
+export const HumanInterventionPolicySchema = z.enum(['never', 'required']);
/**
* Argument Matcher for parameter-level filtering
@@ -116,6 +116,36 @@ export const HumanInterventionResponseSchema = z.object({
.optional(),
});
+/**
+ * User's global intervention configuration
+ * Applied across all tools in the session
+ */
+export interface UserInterventionConfig {
+ /**
+ * Allow list of approved tools (used in 'allow-list' mode)
+ * Format: "identifier/apiName"
+ *
+ * Examples:
+ * - "bash/bash"
+ * - "web-browsing/crawlSinglePage"
+ * - "search/search"
+ */
+ allowList?: string[];
+
+ /**
+ * Tool approval mode
+ * - auto-run: Automatically approve all tools without user consent
+ * - allow-list: Only approve tools in the allow list
+ * - manual: Use tool's own humanIntervention config (default)
+ */
+ approvalMode: 'auto-run' | 'allow-list' | 'manual';
+}
+
+export const UserInterventionConfigSchema = z.object({
+ allowList: z.array(z.string()).optional(),
+ approvalMode: z.enum(['auto-run', 'allow-list', 'manual']),
+});
+
/**
* Parameters for shouldIntervene method
*/
diff --git a/packages/types/src/user/settings/tool.ts b/packages/types/src/user/settings/tool.ts
index d73f05c138d..7f3f6012b10 100644
--- a/packages/types/src/user/settings/tool.ts
+++ b/packages/types/src/user/settings/tool.ts
@@ -1,29 +1,5 @@
-export interface UserToolConfig {
- /**
- * Tool approval mode
- * - auto-run: Automatically approve all tools without user consent
- * - allow-list: Only approve tools in the allow list
- * - manual: Require manual approval for each tool execution
- */
- approvalMode?: 'auto-run' | 'allow-list' | 'manual';
-
- dalle: {
- autoGenerate: boolean;
- };
+import { UserInterventionConfig } from '../../tool';
- /**
- * Tool intervention configuration
- */
- humanIntervention?: {
- /**
- * Allow list of approved tools (used in 'allow-list' mode)
- * Format: "identifier/apiName"
- *
- * Examples:
- * - "web-browsing/crawlSinglePage"
- * - "bash/bash"
- * - "search/search"
- */
- allowList?: string[];
- };
+export interface UserToolConfig {
+ humanIntervention?: UserInterventionConfig;
}
diff --git a/src/features/Conversation/MarkdownElements/remarkPlugins/__snapshots__/createRemarkSelfClosingTagPlugin.test.ts.snap b/src/features/Conversation/MarkdownElements/remarkPlugins/__snapshots__/createRemarkSelfClosingTagPlugin.test.ts.snap
index cc543c8aa51..9b775ff3198 100644
--- a/src/features/Conversation/MarkdownElements/remarkPlugins/__snapshots__/createRemarkSelfClosingTagPlugin.test.ts.snap
+++ b/src/features/Conversation/MarkdownElements/remarkPlugins/__snapshots__/createRemarkSelfClosingTagPlugin.test.ts.snap
@@ -1,5 +1,138 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+exports[`createRemarkSelfClosingTagPlugin > should handle multiple tags in unordered list with directories and files 1`] = `
+{
+ "children": [
+ {
+ "children": [
+ {
+ "position": {
+ "end": {
+ "column": 32,
+ "line": 1,
+ "offset": 31,
+ },
+ "start": {
+ "column": 1,
+ "line": 1,
+ "offset": 0,
+ },
+ },
+ "type": "text",
+ "value": "我已查看了你桌面上 test 文件夹的目录,里面包含以下项目:",
+ },
+ ],
+ "position": {
+ "end": {
+ "column": 32,
+ "line": 1,
+ "offset": 31,
+ },
+ "start": {
+ "column": 1,
+ "line": 1,
+ "offset": 0,
+ },
+ },
+ "type": "paragraph",
+ },
+ {
+ "children": [
+ {
+ "checked": null,
+ "children": [
+ {
+ "data": {
+ "hName": "localFile",
+ "hProperties": {
+ "isDirectory": true,
+ "name": ".config",
+ "path": "/Users/user/Desktop/test/.config",
+ },
+ },
+ "type": "localFile",
+ },
+ ],
+ "position": {
+ "end": {
+ "column": 87,
+ "line": 3,
+ "offset": 119,
+ },
+ "start": {
+ "column": 1,
+ "line": 3,
+ "offset": 33,
+ },
+ },
+ "spread": false,
+ "type": "listItem",
+ },
+ {
+ "checked": null,
+ "children": [
+ {
+ "data": {
+ "hName": "localFile",
+ "hProperties": {
+ "isDirectory": true,
+ "name": ".venv",
+ "path": "/Users/user/Desktop/test/.venv",
+ },
+ },
+ "type": "localFile",
+ },
+ ],
+ "position": {
+ "end": {
+ "column": 79,
+ "line": 4,
+ "offset": 198,
+ },
+ "start": {
+ "column": 1,
+ "line": 4,
+ "offset": 120,
+ },
+ },
+ "spread": false,
+ "type": "listItem",
+ },
+ ],
+ "ordered": false,
+ "position": {
+ "end": {
+ "column": 79,
+ "line": 4,
+ "offset": 198,
+ },
+ "start": {
+ "column": 1,
+ "line": 3,
+ "offset": 33,
+ },
+ },
+ "spread": false,
+ "start": null,
+ "type": "list",
+ },
+ ],
+ "position": {
+ "end": {
+ "column": 79,
+ "line": 4,
+ "offset": 198,
+ },
+ "start": {
+ "column": 1,
+ "line": 1,
+ "offset": 0,
+ },
+ },
+ "type": "root",
+}
+`;
+
exports[`createRemarkSelfClosingTagPlugin > should handle tag within a list item and generate snapshot 1`] = `
{
"children": [
diff --git a/src/features/Conversation/MarkdownElements/remarkPlugins/createRemarkSelfClosingTagPlugin.test.ts b/src/features/Conversation/MarkdownElements/remarkPlugins/createRemarkSelfClosingTagPlugin.test.ts
index 9e70b357b80..152d10cc4ad 100644
--- a/src/features/Conversation/MarkdownElements/remarkPlugins/createRemarkSelfClosingTagPlugin.test.ts
+++ b/src/features/Conversation/MarkdownElements/remarkPlugins/createRemarkSelfClosingTagPlugin.test.ts
@@ -201,4 +201,52 @@ describe('createRemarkSelfClosingTagPlugin', () => {
const tree = processMarkdown(markdown, tagName);
expect(tree).toMatchSnapshot();
});
+
+ it('should handle multiple tags in unordered list with directories and files', () => {
+ const markdown = [
+ '我已查看了你桌面上 test 文件夹的目录,里面包含以下项目:',
+ '',
+ '- <localFile name=".config" path="/Users/user/Desktop/test/.config" isDirectory /> ', // 注意:行尾有 4 个空格
+ '- <localFile name=".venv" path="/Users/user/Desktop/test/.venv" isDirectory />',
+ ].join('\n');
+ const tree = processMarkdown(markdown, tagName);
+
+ // Should have 2 children: a paragraph and a list
+ expect(tree.children).toHaveLength(2);
+
+ // First child should be the introductory paragraph
+ expect(tree.children[0].type).toBe('paragraph');
+
+ // Second child should be the unordered list
+ const listNode = tree.children[1];
+ expect(listNode.type).toBe('list');
+ expect(listNode.ordered).toBe(false);
+
+ // The list should have 2 items
+ expect(listNode.children).toHaveLength(2);
+
+ // Verify first item (.config directory) - this one has trailing spaces after />
+ // When a tag is standalone in a list item, remark doesn't wrap it in a paragraph
+ const firstItem = listNode.children[0];
+ expect(firstItem.type).toBe('listItem');
+ const firstTag = firstItem.children[0];
+ expect(firstTag.type).toBe(tagName);
+ expect(firstTag.data?.hProperties).toEqual({
+ name: '.config',
+ path: '/Users/user/Desktop/test/.config',
+ isDirectory: true,
+ });
+
+ // Verify second item (.venv directory)
+ const secondItem = listNode.children[1];
+ const secondTag = secondItem.children[0];
+ expect(secondTag.type).toBe(tagName);
+ expect(secondTag.data?.hProperties).toEqual({
+ name: '.venv',
+ path: '/Users/user/Desktop/test/.venv',
+ isDirectory: true,
+ });
+
+ expect(tree).toMatchSnapshot();
+ });
});
diff --git a/src/features/Conversation/MarkdownElements/remarkPlugins/createRemarkSelfClosingTagPlugin.ts b/src/features/Conversation/MarkdownElements/remarkPlugins/createRemarkSelfClosingTagPlugin.ts
index 817e25afae9..968bc57e264 100644
--- a/src/features/Conversation/MarkdownElements/remarkPlugins/createRemarkSelfClosingTagPlugin.ts
+++ b/src/features/Conversation/MarkdownElements/remarkPlugins/createRemarkSelfClosingTagPlugin.ts
@@ -25,7 +25,8 @@ export const createRemarkSelfClosingTagPlugin =
(tagName: string): Plugin<[], any> =>
() => {
// Regex for the specific tag, ensure it matches the entire string for HTML check
- const exactTagRegex = new RegExp(`^<${tagName}(\\s+[^>]*?)?\\s*\\/>$`);
+ // Allow trailing whitespace after /> to handle cases where markdown parsers include it
+ const exactTagRegex = new RegExp(`^<${tagName}(\\s+[^>]*?)?\\s*\\/>\\s*$`);
// Regex for finding tags within text
const textTagRegex = new RegExp(`<${tagName}(\\s+[^>]*?)?\\s*\\/>`, 'g');
diff --git a/src/features/Conversation/Messages/Group/Tool/Render/Intervention/Fallback.tsx b/src/features/Conversation/Messages/Group/Tool/Render/Intervention/Fallback.tsx
new file mode 100644
index 00000000000..34201e41ed4
--- /dev/null
+++ b/src/features/Conversation/Messages/Group/Tool/Render/Intervention/Fallback.tsx
@@ -0,0 +1,98 @@
+import { safeParseJSON } from '@lobechat/utils';
+import { ActionIcon } from '@lobehub/ui';
+import { Edit3Icon } from 'lucide-react';
+import { Suspense, memo, useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useChatStore } from '@/store/chat';
+import { useUserStore } from '@/store/user';
+import { toolInterventionSelectors } from '@/store/user/selectors';
+
+import Arguments from '../Arguments';
+import ApprovalActions from './ApprovalActions';
+import KeyValueEditor from './KeyValueEditor';
+import ModeSelector from './ModeSelector';
+
+interface FallbackInterventionProps {
+ apiName: string;
+ id: string;
+ identifier: string;
+ requestArgs: string;
+ toolCallId: string;
+}
+
+const FallbackIntervention = memo<FallbackInterventionProps>(
+ ({ requestArgs, id, identifier, apiName, toolCallId }) => {
+ const { t } = useTranslation('chat');
+ const approvalMode = useUserStore(toolInterventionSelectors.approvalMode);
+ const [isEditing, setIsEditing] = useState(false);
+ const [optimisticUpdatePluginArguments] = useChatStore((s) => [
+ s.optimisticUpdatePluginArguments,
+ ]);
+
+ const handleCancel = useCallback(() => {
+ setIsEditing(false);
+ }, []);
+
+ const handleFinish = useCallback(
+ async (editedObject: Record<string, any>) => {
+ if (!id) return;
+
+ try {
+ const newArgsString = JSON.stringify(editedObject, null, 2);
+
+ if (newArgsString !== requestArgs) {
+ await optimisticUpdatePluginArguments(id, editedObject, true);
+ }
+ setIsEditing(false);
+ } catch (error) {
+ console.error('Error stringifying arguments:', error);
+ }
+ },
+ [requestArgs, id],
+ );
+
+ if (isEditing)
+ return (
+ <Suspense fallback={<Arguments arguments={requestArgs} />}>
+ <KeyValueEditor
+ initialValue={safeParseJSON(requestArgs || '')}
+ onCancel={handleCancel}
+ onFinish={handleFinish}
+ />
+ </Suspense>
+ );
+
+ return (
+ <Flexbox gap={12}>
+ <Arguments
+ actions={
+ <ActionIcon
+ icon={Edit3Icon}
+ onClick={() => {
+ setIsEditing(true);
+ }}
+ size={'small'}
+ title={t('edit', { ns: 'common' })}
+ />
+ }
+ arguments={requestArgs}
+ />
+
+ <Flexbox horizontal justify={'space-between'}>
+ <ModeSelector />
+ <ApprovalActions
+ apiName={apiName}
+ approvalMode={approvalMode}
+ identifier={identifier}
+ messageId={id}
+ toolCallId={toolCallId}
+ />
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+export default FallbackIntervention;
diff --git a/src/features/Conversation/Messages/Group/Tool/Render/Intervention/ModeSelector.tsx b/src/features/Conversation/Messages/Group/Tool/Render/Intervention/ModeSelector.tsx
index 8d4397e3e82..77897cf04f1 100644
--- a/src/features/Conversation/Messages/Group/Tool/Render/Intervention/ModeSelector.tsx
+++ b/src/features/Conversation/Messages/Group/Tool/Render/Intervention/ModeSelector.tsx
@@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next';
import { Center } from 'react-layout-kit';
import { useUserStore } from '@/store/user';
+import { toolInterventionSelectors } from '@/store/user/selectors';
import { ApprovalMode } from './index';
@@ -39,10 +40,8 @@ const useStyles = createStyles(({ css, token }) => ({
const ModeSelector = memo(() => {
const { t } = useTranslation('chat');
const { styles } = useStyles();
- const [approvalMode, setSettings] = useUserStore((s) => [
- s.settings.tool?.approvalMode || 'manual',
- s.setSettings,
- ]);
+ const approvalMode = useUserStore(toolInterventionSelectors.approvalMode);
+ const updateHumanIntervention = useUserStore((s) => s.updateHumanIntervention);
const modeLabels = useMemo(
() => ({
@@ -55,9 +54,9 @@ const ModeSelector = memo(() => {
const handleModeChange = useCallback(
async (mode: ApprovalMode) => {
- await setSettings({ tool: { approvalMode: mode } });
+ await updateHumanIntervention({ approvalMode: mode });
},
- [setSettings],
+ [updateHumanIntervention],
);
const menuItems = useMemo<MenuProps['items']>(
diff --git a/src/features/Conversation/Messages/Group/Tool/Render/Intervention/index.tsx b/src/features/Conversation/Messages/Group/Tool/Render/Intervention/index.tsx
index 42e628ee653..8e9373987de 100644
--- a/src/features/Conversation/Messages/Group/Tool/Render/Intervention/index.tsx
+++ b/src/features/Conversation/Messages/Group/Tool/Render/Intervention/index.tsx
@@ -1,15 +1,15 @@
import { safeParseJSON } from '@lobechat/utils';
-import { ActionIcon } from '@lobehub/ui';
-import { Edit3Icon } from 'lucide-react';
import { Suspense, memo, useCallback, useState } from 'react';
-import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
import { useChatStore } from '@/store/chat';
import { useUserStore } from '@/store/user';
+import { toolInterventionSelectors } from '@/store/user/selectors';
+import { BuiltinToolInterventions } from '@/tools/interventions';
import Arguments from '../Arguments';
import ApprovalActions from './ApprovalActions';
+import Fallback from './Fallback';
import KeyValueEditor from './KeyValueEditor';
import ModeSelector from './ModeSelector';
@@ -25,8 +25,7 @@ interface InterventionProps {
const Intervention = memo<InterventionProps>(
({ requestArgs, id, identifier, apiName, toolCallId }) => {
- const { t } = useTranslation('chat');
- const approvalMode = useUserStore((s) => s.settings.tool?.approvalMode || 'manual');
+ const approvalMode = useUserStore(toolInterventionSelectors.approvalMode);
const [isEditing, setIsEditing] = useState(false);
const [optimisticUpdatePluginArguments] = useChatStore((s) => [
s.optimisticUpdatePluginArguments,
@@ -53,45 +52,50 @@ const Intervention = memo<InterventionProps>(
},
[requestArgs, id],
);
+ const BuiltinToolInterventionRender = BuiltinToolInterventions[identifier];
- if (isEditing)
- return (
- <Suspense fallback={<Arguments arguments={requestArgs} />}>
- <KeyValueEditor
- initialValue={safeParseJSON(requestArgs || '')}
- onCancel={handleCancel}
- onFinish={handleFinish}
- />
- </Suspense>
- );
-
- return (
- <Flexbox gap={12}>
- <Arguments
- actions={
- <ActionIcon
- icon={Edit3Icon}
- onClick={() => {
- setIsEditing(true);
- }}
- size={'small'}
- title={t('edit', { ns: 'common' })}
+ if (BuiltinToolInterventionRender) {
+ if (isEditing)
+ return (
+ <Suspense fallback={<Arguments arguments={requestArgs} />}>
+ <KeyValueEditor
+ initialValue={safeParseJSON(requestArgs || '')}
+ onCancel={handleCancel}
+ onFinish={handleFinish}
/>
- }
- arguments={requestArgs}
- />
+ </Suspense>
+ );
- <Flexbox horizontal justify={'space-between'}>
- <ModeSelector />
- <ApprovalActions
+ return (
+ <Flexbox gap={12}>
+ <BuiltinToolInterventionRender
apiName={apiName}
- approvalMode={approvalMode}
+ args={safeParseJSON(requestArgs || '')}
identifier={identifier}
messageId={id}
- toolCallId={toolCallId}
/>
+ <Flexbox horizontal justify={'space-between'}>
+ <ModeSelector />
+ <ApprovalActions
+ apiName={apiName}
+ approvalMode={approvalMode}
+ identifier={identifier}
+ messageId={id}
+ toolCallId={toolCallId}
+ />
+ </Flexbox>
</Flexbox>
- </Flexbox>
+ );
+ }
+
+ return (
+ <Fallback
+ apiName={apiName}
+ id={id}
+ identifier={identifier}
+ requestArgs={requestArgs}
+ toolCallId={toolCallId}
+ />
);
},
);
diff --git a/src/features/Conversation/Messages/Group/Tool/Render/index.tsx b/src/features/Conversation/Messages/Group/Tool/Render/index.tsx
index 7e0061b977d..d1622828b76 100644
--- a/src/features/Conversation/Messages/Group/Tool/Render/index.tsx
+++ b/src/features/Conversation/Messages/Group/Tool/Render/index.tsx
@@ -1,10 +1,12 @@
import { LOADING_FLAT } from '@lobechat/const';
import { ChatToolResult, ToolIntervention } from '@lobechat/types';
import { Suspense, memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
import CustomRender from './CustomRender';
import ErrorResponse from './ErrorResponse';
import Intervention from './Intervention';
+import ModeSelector from './Intervention/ModeSelector';
import LoadingPlaceholder from './LoadingPlaceholder';
import RejectedResponse from './RejectedResponse';
@@ -99,24 +101,29 @@ const Render = memo<RenderProps>(
return (
<Suspense fallback={placeholder}>
- <CustomRender
- content={result.content || ''}
- id={toolCallId}
- plugin={
- type
- ? ({
- apiName,
- arguments: requestArgs || '',
- identifier,
- type,
- } as any)
- : undefined
- }
- pluginState={result.state}
- requestArgs={requestArgs}
- setShowPluginRender={setShowPluginRender}
- showPluginRender={showPluginRender}
- />
+ <Flexbox gap={8}>
+ <CustomRender
+ content={result.content || ''}
+ id={toolCallId}
+ plugin={
+ type
+ ? ({
+ apiName,
+ arguments: requestArgs || '',
+ identifier,
+ type,
+ } as any)
+ : undefined
+ }
+ pluginState={result.state}
+ requestArgs={requestArgs}
+ setShowPluginRender={setShowPluginRender}
+ showPluginRender={showPluginRender}
+ />
+ <div>
+ <ModeSelector />
+ </div>
+ </Flexbox>
</Suspense>
);
},
diff --git a/src/features/LocalFile/LocalFile.tsx b/src/features/LocalFile/LocalFile.tsx
index e0828b896d6..f22becbf713 100644
--- a/src/features/LocalFile/LocalFile.tsx
+++ b/src/features/LocalFile/LocalFile.tsx
@@ -1,5 +1,9 @@
+import { Button } from '@lobehub/ui';
+import { Popover, Space } from 'antd';
import { createStyles } from 'antd-style';
+import { ExternalLink, FolderOpen } from 'lucide-react';
import React from 'react';
+import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
import FileIcon from '@/components/FileIcon';
@@ -13,7 +17,7 @@ const useStyles = createStyles(({ css, token }) => ({
padding-inline: 4px 8px;
border-radius: 4px;
- color: ${token.colorTextSecondary};
+ color: ${token.colorText};
:hover {
color: ${token.colorText};
@@ -39,19 +43,25 @@ interface LocalFileProps {
export const LocalFile = ({ name, path, isDirectory = false }: LocalFileProps) => {
const { styles } = useStyles();
- const handleClick = () => {
- if (!path) return;
+ const { t } = useTranslation('components');
+ const handleOpenFile = () => {
+ if (!path) return;
localFileService.openLocalFileOrFolder(path, isDirectory);
};
- return (
+ const handleOpenFolder = () => {
+ if (!path) return;
+ localFileService.openFileFolder(path);
+ };
+
+ const fileContent = (
<Flexbox
align={'center'}
className={styles.container}
gap={4}
horizontal
- onClick={handleClick}
+ onClick={isDirectory ? handleOpenFile : undefined}
style={{ display: 'inline-flex', verticalAlign: 'middle' }}
>
<FileIcon fileName={name} isDirectory={isDirectory} size={22} variant={'raw'} />
@@ -60,4 +70,44 @@ export const LocalFile = ({ name, path, isDirectory = false }: LocalFileProps) =
</Flexbox>
</Flexbox>
);
+
+ // Directory: no popover, just click to open
+ if (isDirectory) {
+ return fileContent;
+ }
+
+ // File: show popover with two actions
+ const popoverContent = (
+ <Space.Compact>
+ <Button
+ icon={ExternalLink}
+ onClick={handleOpenFile}
+ size="small"
+ title={t('LocalFile.action.open')}
+ >
+ {t('LocalFile.action.open')}
+ </Button>
+ <Button
+ icon={FolderOpen}
+ onClick={handleOpenFolder}
+ size="small"
+ title={t('LocalFile.action.showInFolder')}
+ >
+ {t('LocalFile.action.showInFolder')}
+ </Button>
+ </Space.Compact>
+ );
+
+ return (
+ <Popover
+ arrow={false}
+ content={popoverContent}
+ styles={{
+ body: { padding: 0 },
+ }}
+ trigger={['hover']}
+ >
+ {fileContent}
+ </Popover>
+ );
};
diff --git a/src/locales/default/components.ts b/src/locales/default/components.ts
index 77a4d441a14..5d937f271bc 100644
--- a/src/locales/default/components.ts
+++ b/src/locales/default/components.ts
@@ -108,6 +108,12 @@ export default {
keyPlaceholder: '键',
valuePlaceholder: '值',
},
+ LocalFile: {
+ action: {
+ open: '打开',
+ showInFolder: '在文件夹中显示',
+ },
+ },
MaxTokenSlider: {
unlimited: '无限制',
},
diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.ts
index f0432bdc0b2..548748011b3 100644
--- a/src/locales/default/plugin.ts
+++ b/src/locales/default/plugin.ts
@@ -256,6 +256,7 @@ export default {
moveLocalFiles: '移动文件',
readLocalFile: '读取文件内容',
renameLocalFile: '重命名',
+ runCommand: '执行代码',
searchLocalFiles: '搜索文件',
writeLocalFile: '写入文件',
},
diff --git a/src/services/electron/localFileService.ts b/src/services/electron/localFileService.ts
index 6720c5e15d8..d025727637d 100644
--- a/src/services/electron/localFileService.ts
+++ b/src/services/electron/localFileService.ts
@@ -98,6 +98,10 @@ class LocalFileService {
return this.openLocalFile({ path });
}
}
+
+ async openFileFolder(path: string) {
+ return this.openLocalFolder({ isDirectory: false, path });
+ }
}
export const localFileService = new LocalFileService();
diff --git a/src/store/chat/agents/GeneralChatAgent.ts b/src/store/chat/agents/GeneralChatAgent.ts
index e40bbf962cb..723011d615f 100644
--- a/src/store/chat/agents/GeneralChatAgent.ts
+++ b/src/store/chat/agents/GeneralChatAgent.ts
@@ -54,6 +54,7 @@ export class GeneralChatAgent implements Agent {
/**
* Check if tool calls need human intervention
+ * Combines user's global config with tool's own config
* Returns [toolsNeedingIntervention, toolsToExecute]
*/
private checkInterventionNeeded(
@@ -63,7 +64,31 @@ export class GeneralChatAgent implements Agent {
const toolsNeedingIntervention: ChatToolPayload[] = [];
const toolsToExecute: ChatToolPayload[] = [];
+ // Get user config (default to 'manual' mode)
+ const userConfig = state.userInterventionConfig || { approvalMode: 'manual' };
+ const { approvalMode, allowList = [] } = userConfig;
+
for (const toolCalling of toolsCalling) {
+ const { identifier, apiName } = toolCalling;
+ const toolKey = `${identifier}/${apiName}`;
+
+ // Priority 1: User config is 'auto-run', all tools execute directly
+ if (approvalMode === 'auto-run') {
+ toolsToExecute.push(toolCalling);
+ continue;
+ }
+
+ // Priority 2: User config is 'allow-list', check if tool is in whitelist
+ if (approvalMode === 'allow-list') {
+ if (allowList.includes(toolKey)) {
+ toolsToExecute.push(toolCalling);
+ } else {
+ toolsNeedingIntervention.push(toolCalling);
+ }
+ continue;
+ }
+
+ // Priority 3: User config is 'manual' (default), use tool's own config
const config = this.getToolInterventionConfig(toolCalling, state);
// Parse arguments for intervention checking
@@ -82,7 +107,7 @@ export class GeneralChatAgent implements Agent {
if (policy === 'never') {
toolsToExecute.push(toolCalling);
} else {
- // 'require' or 'first' (when not confirmed) requires intervention
+ // 'required' or undefined requires intervention
toolsNeedingIntervention.push(toolCalling);
}
}
diff --git a/src/store/chat/agents/__tests__/GeneralChatAgent.test.ts b/src/store/chat/agents/__tests__/GeneralChatAgent.test.ts
index 05792da67a5..6760591e3bd 100644
--- a/src/store/chat/agents/__tests__/GeneralChatAgent.test.ts
+++ b/src/store/chat/agents/__tests__/GeneralChatAgent.test.ts
@@ -601,5 +601,178 @@ describe('GeneralChatAgent', () => {
},
]);
});
+
+ it('should execute all tools when user approvalMode is auto-run', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ sessionId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const toolCall: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'dangerous-tool',
+ apiName: 'delete',
+ arguments: '{}',
+ type: 'default',
+ };
+
+ const state = createMockState({
+ toolManifestMap: {
+ 'dangerous-tool': {
+ identifier: 'dangerous-tool',
+ humanIntervention: 'required', // Tool requires approval
+ },
+ },
+ userInterventionConfig: {
+ approvalMode: 'auto-run', // But user config overrides
+ allowList: [],
+ },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ // Should execute directly despite tool requiring approval
+ expect(result).toEqual([
+ {
+ type: 'call_tool',
+ payload: {
+ parentMessageId: 'msg-1',
+ toolCalling: toolCall,
+ },
+ },
+ ]);
+ });
+
+ it('should respect allowList when approvalMode is allow-list', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ sessionId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const allowedTool: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'bash',
+ apiName: 'bash',
+ arguments: '{"command":"ls"}',
+ type: 'builtin',
+ };
+
+ const blockedTool: ChatToolPayload = {
+ id: 'call-2',
+ identifier: 'bash',
+ apiName: 'dangerous-command',
+ arguments: '{"command":"rm -rf"}',
+ type: 'builtin',
+ };
+
+ const state = createMockState({
+ toolManifestMap: {
+ bash: {
+ identifier: 'bash',
+ humanIntervention: 'never', // Tool doesn't require approval by default
+ },
+ },
+ userInterventionConfig: {
+ approvalMode: 'allow-list',
+ allowList: ['bash/bash'], // Only bash/bash is allowed
+ },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [allowedTool, blockedTool],
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ // Should execute allowed tool first, then request approval for blocked tool
+ expect(result).toEqual([
+ {
+ type: 'call_tool',
+ payload: {
+ parentMessageId: 'msg-1',
+ toolCalling: allowedTool,
+ },
+ },
+ {
+ type: 'request_human_approve',
+ pendingToolsCalling: [blockedTool],
+ reason: 'human_intervention_required',
+ },
+ ]);
+ });
+
+ it('should use tool config when approvalMode is manual', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ sessionId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const safeTool: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'web-search',
+ apiName: 'search',
+ arguments: '{}',
+ type: 'default',
+ };
+
+ const dangerousTool: ChatToolPayload = {
+ id: 'call-2',
+ identifier: 'bash',
+ apiName: 'bash',
+ arguments: '{}',
+ type: 'builtin',
+ };
+
+ const state = createMockState({
+ toolManifestMap: {
+ 'web-search': {
+ identifier: 'web-search',
+ humanIntervention: 'never', // Safe tool
+ },
+ 'bash': {
+ identifier: 'bash',
+ humanIntervention: 'required', // Dangerous tool
+ },
+ },
+ userInterventionConfig: {
+ approvalMode: 'manual', // Use tool's own config
+ },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [safeTool, dangerousTool],
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ // Should execute safe tool, request approval for dangerous tool
+ expect(result).toEqual([
+ {
+ type: 'call_tool',
+ payload: {
+ parentMessageId: 'msg-1',
+ toolCalling: safeTool,
+ },
+ },
+ {
+ type: 'request_human_approve',
+ pendingToolsCalling: [dangerousTool],
+ reason: 'human_intervention_required',
+ },
+ ]);
+ });
});
});
diff --git a/src/store/chat/slices/aiChat/actions/conversationControl.ts b/src/store/chat/slices/aiChat/actions/conversationControl.ts
index e8f57620410..b1b3b57b58e 100644
--- a/src/store/chat/slices/aiChat/actions/conversationControl.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationControl.ts
@@ -1,13 +1,10 @@
/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
// Disable the auto sort key eslint rule to make the code more logic and readable
-import { AgentRuntime, type AgentRuntimeContext } from '@lobechat/agent-runtime';
+import { type AgentRuntimeContext } from '@lobechat/agent-runtime';
import { MESSAGE_CANCEL_FLAT } from '@lobechat/const';
import { produce } from 'immer';
import { StateCreator } from 'zustand/vanilla';
-import { getAgentStoreState } from '@/store/agent';
-import { agentSelectors } from '@/store/agent/slices/chat';
-import { createAgentToolsEngine } from '@/store/chat/agents/createToolEngine';
import { ChatStore } from '@/store/chat/store';
import { setNamespace } from '@/utils/storeDebug';
@@ -146,7 +143,7 @@ export const conversationControl: StateCreator<
}
},
approveToolCalling: async (toolMessageId) => {
- const { activeId, activeTopicId, activeThreadId, internal_execAgentRuntime } = get();
+ const { activeThreadId, internal_execAgentRuntime } = get();
// 1. Get tool message and verify it exists
const toolMessage = dbMessageSelectors.getDbMessageById(toolMessageId)(get());
@@ -158,51 +155,22 @@ export const conversationControl: StateCreator<
// 3. Get current messages for state construction
const currentMessages = displayMessageSelectors.mainAIChats(get());
- // 4. Get agent configuration and tools information
- const agentStoreState = getAgentStoreState();
- const agentConfigData = agentSelectors.currentAgentConfig(agentStoreState);
-
- const toolsEngine = createAgentToolsEngine({
- model: agentConfigData.model,
- provider: agentConfigData.provider!,
- });
- const { enabledToolIds } = toolsEngine.generateToolsDetailed({
- model: agentConfigData.model,
- provider: agentConfigData.provider!,
- toolIds: agentConfigData.plugins,
- });
- const toolManifestMap = Object.fromEntries(
- toolsEngine.getEnabledPluginManifests(enabledToolIds).entries(),
- );
-
- // 5. Construct AgentState
- const state = AgentRuntime.createInitialState({
- sessionId: activeId,
+ // 4. Create agent state and context with user intervention config
+ const { state, context: initialContext } = get().internal_createAgentState({
messages: currentMessages,
- maxSteps: 400,
- metadata: {
- sessionId: activeId,
- topicId: activeTopicId,
- threadId: activeThreadId,
- },
- toolManifestMap,
+ parentMessageId: toolMessageId,
+ threadId: activeThreadId,
});
- console.log('toolMessage:', toolMessage);
- // 6. Construct AgentRuntimeContext with 'human_approved_tool' phase
+ // 5. Override context with 'human_approved_tool' phase
const context: AgentRuntimeContext = {
+ ...initialContext,
phase: 'human_approved_tool',
payload: {
approvedToolCall: toolMessage.plugin,
parentMessageId: toolMessageId,
skipCreateToolMessage: true,
},
- session: {
- sessionId: activeId,
- messageCount: currentMessages.length,
- status: 'running',
- stepCount: 0,
- },
};
// 7. Execute agent runtime from tool message position
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index d19eb35dd8a..ec046956065 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -26,6 +26,8 @@ import { createAgentExecutors } from '@/store/chat/agents/createAgentExecutors';
import { createAgentToolsEngine } from '@/store/chat/agents/createToolEngine';
import { ChatStore } from '@/store/chat/store';
import { getFileStoreState } from '@/store/file/store';
+import { toolInterventionSelectors } from '@/store/user/selectors';
+import { getUserStoreState } from '@/store/user/store';
import { setNamespace } from '@/utils/storeDebug';
import { topicSelectors } from '../../../selectors';
@@ -54,6 +56,19 @@ interface ProcessMessageParams {
* Core streaming execution actions for AI chat
*/
export interface StreamingExecutorAction {
+ /**
+ * Creates initial agent state and context with user intervention config
+ */
+ internal_createAgentState: (params: {
+ messages: UIChatMessage[];
+ parentMessageId: string;
+ threadId?: string;
+ initialState?: AgentState;
+ initialContext?: AgentRuntimeContext;
+ }) => {
+ state: AgentState;
+ context: AgentRuntimeContext;
+ };
/**
* Retrieves an AI-generated chat message from the backend service with streaming
*/
@@ -106,6 +121,73 @@ export const streamingExecutor: StateCreator<
[],
StreamingExecutorAction
> = (set, get) => ({
+ internal_createAgentState: ({
+ messages,
+ parentMessageId,
+ threadId,
+ initialState,
+ initialContext,
+ }) => {
+ const { activeId, activeTopicId } = get();
+ const agentStoreState = getAgentStoreState();
+ const agentConfigData = agentSelectors.currentAgentConfig(agentStoreState);
+
+ // Get tools manifest map
+ const toolsEngine = createAgentToolsEngine({
+ model: agentConfigData.model,
+ provider: agentConfigData.provider!,
+ });
+ const { enabledToolIds } = toolsEngine.generateToolsDetailed({
+ model: agentConfigData.model,
+ provider: agentConfigData.provider!,
+ toolIds: agentConfigData.plugins,
+ });
+ const toolManifestMap = Object.fromEntries(
+ toolsEngine.getEnabledPluginManifests(enabledToolIds).entries(),
+ );
+
+ // Get user intervention config
+ const userStore = getUserStoreState();
+ const userInterventionConfig = {
+ approvalMode: toolInterventionSelectors.approvalMode(userStore),
+ allowList: toolInterventionSelectors.allowList(userStore),
+ };
+
+ // Create initial state or use provided state
+ const state =
+ initialState ||
+ AgentRuntime.createInitialState({
+ sessionId: activeId,
+ messages,
+ maxSteps: 400,
+ metadata: {
+ sessionId: activeId,
+ topicId: activeTopicId,
+ threadId,
+ },
+ toolManifestMap,
+ userInterventionConfig,
+ });
+
+ // Create initial context or use provided context
+ const context: AgentRuntimeContext = initialContext || {
+ phase: 'init',
+ payload: {
+ model: agentConfigData.model,
+ provider: agentConfigData.provider,
+ parentMessageId,
+ },
+ session: {
+ sessionId: activeId,
+ messageCount: messages.length,
+ status: state.status,
+ stepCount: 0,
+ },
+ };
+
+ return { state, context };
+ },
+
internal_fetchAIChatMessage: async ({ messages, messageId, params, provider, model }) => {
const {
internal_toggleChatLoading,
@@ -469,16 +551,6 @@ export const streamingExecutor: StateCreator<
},
});
- const toolsEngine = createAgentToolsEngine({ model: model, provider: provider! });
- const { enabledToolIds } = toolsEngine.generateToolsDetailed({
- model: model,
- provider: provider!,
- toolIds: agentConfigData.plugins,
- });
- const toolManifestMap = Object.fromEntries(
- toolsEngine.getEnabledPluginManifests(enabledToolIds).entries(),
- );
-
const runtime = new AgentRuntime(agent, {
executors: createAgentExecutors({
get,
@@ -489,33 +561,18 @@ export const streamingExecutor: StateCreator<
}),
});
- // Create initial state or use provided state
- let state =
- params.initialState ||
- AgentRuntime.createInitialState({
- sessionId: activeId,
+ // Create agent state and context with user intervention config
+ const { state: initialAgentState, context: initialAgentContext } =
+ get().internal_createAgentState({
messages,
- // Prevent infinite loops
- maxSteps: 400,
- metadata: {
- sessionId: activeId,
- topicId: activeTopicId,
- threadId: params.threadId,
- },
- toolManifestMap,
+ parentMessageId: params.parentMessageId,
+ threadId: params.threadId,
+ initialState: params.initialState,
+ initialContext: params.initialContext,
});
- // Initial context - use provided context or create default 'init' phase
- let nextContext: AgentRuntimeContext = params.initialContext || {
- phase: 'init',
- payload: { model, provider, parentMessageId: params.parentMessageId },
- session: {
- sessionId: activeId,
- messageCount: messages.length,
- status: state.status,
- stepCount: 0,
- },
- };
+ let state = initialAgentState;
+ let nextContext = initialAgentContext;
log(
'[internal_execAgentRuntime] Agent runtime loop start, initial phase: %s',
diff --git a/src/store/user/selectors.ts b/src/store/user/selectors.ts
index 6440e909d2f..0ee482008b5 100644
--- a/src/store/user/selectors.ts
+++ b/src/store/user/selectors.ts
@@ -4,5 +4,6 @@ export {
keyVaultsConfigSelectors,
settingsSelectors,
systemAgentSelectors,
+ toolInterventionSelectors,
userGeneralSettingsSelectors,
} from './slices/settings/selectors';
diff --git a/src/store/user/slices/settings/action.ts b/src/store/user/slices/settings/action.ts
index 836fc2febb5..e792a3fad9f 100644
--- a/src/store/user/slices/settings/action.ts
+++ b/src/store/user/slices/settings/action.ts
@@ -26,6 +26,10 @@ export interface UserSettingsAction {
setSettings: (settings: PartialDeep<UserSettings>) => Promise<void>;
updateDefaultAgent: (agent: PartialDeep<LobeAgentSettings>) => Promise<void>;
updateGeneralConfig: (settings: Partial<UserGeneralConfig>) => Promise<void>;
+ updateHumanIntervention: (config: {
+ allowList?: string[];
+ approvalMode?: 'auto-run' | 'allow-list' | 'manual';
+ }) => Promise<void>;
updateKeyVaults: (settings: Partial<UserKeyVaults>) => Promise<void>;
updateSystemAgent: (
@@ -111,6 +115,14 @@ export const createSettingsSlice: StateCreator<
updateGeneralConfig: async (general) => {
await get().setSettings({ general });
},
+ updateHumanIntervention: async (config) => {
+ const current = get().settings.tool?.humanIntervention || {};
+ await get().setSettings({
+ tool: {
+ humanIntervention: { ...current, ...config },
+ },
+ });
+ },
updateKeyVaults: async (keyVaults) => {
await get().setSettings({ keyVaults });
},
diff --git a/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap b/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap
index e97cc8dc7c1..8baae5b1feb 100644
--- a/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap
+++ b/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap
@@ -95,13 +95,6 @@ exports[`settingsSelectors > currentTTS > should merge DEFAULT_TTS_CONFIG and s.
}
`;
-exports[`settingsSelectors > dalleConfig > should return the dalle configuration 1`] = `
-{
- "apiKey": "dalle-api-key",
- "autoGenerate": true,
-}
-`;
-
exports[`settingsSelectors > defaultAgent > should merge DEFAULT_AGENT and s.settings.defaultAgent correctly 1`] = `
{
"config": {
diff --git a/src/store/user/slices/settings/selectors/index.ts b/src/store/user/slices/settings/selectors/index.ts
index 714f0bd4390..8660ff5e517 100644
--- a/src/store/user/slices/settings/selectors/index.ts
+++ b/src/store/user/slices/settings/selectors/index.ts
@@ -2,3 +2,4 @@ export { userGeneralSettingsSelectors } from './general';
export { keyVaultsConfigSelectors } from './keyVaults';
export { settingsSelectors } from './settings';
export { systemAgentSelectors } from './systemAgent';
+export { toolInterventionSelectors } from './toolIntervention';
diff --git a/src/store/user/slices/settings/selectors/settings.test.ts b/src/store/user/slices/settings/selectors/settings.test.ts
index bfbe739d1ea..35f3a83733d 100644
--- a/src/store/user/slices/settings/selectors/settings.test.ts
+++ b/src/store/user/slices/settings/selectors/settings.test.ts
@@ -120,43 +120,6 @@ describe('settingsSelectors', () => {
});
});
- describe('dalleConfig', () => {
- it('should return the dalle configuration', () => {
- const s = {
- settings: {
- tool: {
- dalle: {
- apiKey: 'dalle-api-key',
- autoGenerate: true,
- },
- },
- },
- } as unknown as UserStore;
-
- const result = settingsSelectors.dalleConfig(s);
-
- expect(result).toMatchSnapshot();
- });
- });
-
- describe('isDalleAutoGenerating', () => {
- it('should return the autoGenerate flag from dalle configuration', () => {
- const s = {
- settings: {
- tool: {
- dalle: {
- autoGenerate: true,
- },
- },
- },
- } as unknown as UserStore;
-
- const result = settingsSelectors.isDalleAutoGenerating(s);
-
- expect(result).toBe(true);
- });
- });
-
describe('getProviderConfigById', () => {
it('should return the provider config for a given provider id', () => {
const providerConfig = {
diff --git a/src/store/user/slices/settings/selectors/settings.ts b/src/store/user/slices/settings/selectors/settings.ts
index ed471175e8a..ac6003bc569 100644
--- a/src/store/user/slices/settings/selectors/settings.ts
+++ b/src/store/user/slices/settings/selectors/settings.ts
@@ -36,9 +36,6 @@ const defaultAgentMeta = (s: UserStore) => merge(DEFAULT_AGENT_META, defaultAgen
const exportSettings = currentSettings;
-const dalleConfig = (s: UserStore) => currentSettings(s).tool?.dalle || {};
-const isDalleAutoGenerating = (s: UserStore) => currentSettings(s).tool?.dalle?.autoGenerate;
-
const currentSystemAgent = (s: UserStore) =>
merge(DEFAULT_SYSTEM_AGENT_CONFIG, currentSettings(s).systemAgent);
@@ -50,12 +47,10 @@ export const settingsSelectors = {
currentSettings,
currentSystemAgent,
currentTTS,
- dalleConfig,
defaultAgent,
defaultAgentConfig,
defaultAgentMeta,
exportSettings,
getHotkeyById,
- isDalleAutoGenerating,
providerConfig: getProviderConfigById,
};
diff --git a/src/store/user/slices/settings/selectors/toolIntervention.ts b/src/store/user/slices/settings/selectors/toolIntervention.ts
new file mode 100644
index 00000000000..ef540d4160a
--- /dev/null
+++ b/src/store/user/slices/settings/selectors/toolIntervention.ts
@@ -0,0 +1,17 @@
+import type { UserStore } from '@/store/user';
+
+import { currentSettings } from './settings';
+
+const humanInterventionConfig = (s: UserStore) => currentSettings(s).tool?.humanIntervention || {};
+
+const interventionApprovalMode = (s: UserStore) =>
+ currentSettings(s).tool?.humanIntervention?.approvalMode || 'manual';
+
+const interventionAllowList = (s: UserStore) =>
+ currentSettings(s).tool?.humanIntervention?.allowList || [];
+
+export const toolInterventionSelectors = {
+ allowList: interventionAllowList,
+ approvalMode: interventionApprovalMode,
+ config: humanInterventionConfig,
+};
diff --git a/src/tools/interventions.ts b/src/tools/interventions.ts
new file mode 100644
index 00000000000..f16d2bbcb29
--- /dev/null
+++ b/src/tools/interventions.ts
@@ -0,0 +1,8 @@
+import { BuiltinIntervention } from '@lobechat/types';
+
+import { LocalSystemManifest } from './local-system';
+import LocalSystem from './local-system/Intervention';
+
+export const BuiltinToolInterventions: Record<string, BuiltinIntervention> = {
+ [LocalSystemManifest.identifier]: LocalSystem as BuiltinIntervention,
+};
diff --git a/src/tools/local-system/Intervention/RunCommand/index.tsx b/src/tools/local-system/Intervention/RunCommand/index.tsx
new file mode 100644
index 00000000000..ac2905a8a73
--- /dev/null
+++ b/src/tools/local-system/Intervention/RunCommand/index.tsx
@@ -0,0 +1,56 @@
+import { RunCommandParams } from '@lobechat/electron-client-ipc';
+import { Highlighter, Text } from '@lobehub/ui';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+const formatTimeout = (ms?: number) => {
+ if (!ms) return null;
+
+ const seconds = ms / 1000;
+
+ // >= 60s 显示分钟
+ if (seconds >= 60) {
+ const minutes = seconds / 60;
+ return `${minutes.toFixed(1)}min`;
+ }
+
+ // >= 1s 显示秒
+ if (seconds >= 1) {
+ return `${seconds.toFixed(1)}s`;
+ }
+
+ // < 1s 显示毫秒
+ return `${ms}ms`;
+};
+
+interface RunCommandProps extends RunCommandParams {
+ messageId: string;
+}
+
+const RunCommand = memo<RunCommandProps>(({ description, command, timeout }) => {
+ return (
+ <Flexbox gap={8}>
+ <Flexbox horizontal justify={'space-between'}>
+ {description && <Text>{description}</Text>}
+ {timeout && (
+ <Text style={{ fontSize: 12 }} type={'secondary'}>
+ timeout: {formatTimeout(timeout)}
+ </Text>
+ )}
+ </Flexbox>
+ {command && (
+ <Highlighter
+ language={'sh'}
+ showLanguage={false}
+ style={{ padding: '4px 8px' }}
+ variant={'outlined'}
+ wrap
+ >
+ {command}
+ </Highlighter>
+ )}
+ </Flexbox>
+ );
+});
+
+export default RunCommand;
diff --git a/src/tools/local-system/Intervention/index.tsx b/src/tools/local-system/Intervention/index.tsx
new file mode 100644
index 00000000000..1fbc9ec4080
--- /dev/null
+++ b/src/tools/local-system/Intervention/index.tsx
@@ -0,0 +1,17 @@
+import { RunCommandParams } from '@lobechat/electron-client-ipc';
+import { BuiltinInterventionProps } from '@lobechat/types';
+import { memo } from 'react';
+
+import RunCommand from './RunCommand';
+
+const Intervention = memo<BuiltinInterventionProps<RunCommandParams>>(
+ ({ apiName, args, messageId }) => {
+ if (apiName === 'runCommand') {
+ return <RunCommand {...args} messageId={messageId} />;
+ }
+
+ return null;
+ },
+);
+
+export default Intervention;
diff --git a/src/tools/local-system/Render/RunCommand/index.tsx b/src/tools/local-system/Render/RunCommand/index.tsx
index 1d0f51e62fe..aaab00855b0 100644
--- a/src/tools/local-system/Render/RunCommand/index.tsx
+++ b/src/tools/local-system/Render/RunCommand/index.tsx
@@ -1,35 +1,114 @@
-import { RunCommandParams } from '@lobechat/electron-client-ipc';
+import { CheckCircleFilled, CloseCircleFilled } from '@ant-design/icons';
+import { RunCommandParams, RunCommandResult } from '@lobechat/electron-client-ipc';
import { ChatMessagePluginError } from '@lobechat/types';
-import { Terminal } from '@xterm/xterm';
-import '@xterm/xterm/css/xterm.css';
-import { memo, useEffect, useRef } from 'react';
+import { ActionIcon, Block, Highlighter, Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { ChevronDown, ChevronUp } from 'lucide-react';
+import { memo, useState } from 'react';
+import { Flexbox } from 'react-layout-kit';
-import { LocalReadFileState } from '@/tools/local-system/type';
+const useStyles = createStyles(({ css, token }) => ({
+ container: css`
+ overflow: hidden;
+ padding-inline: 8px 0;
+ `,
+ head: css`
+ font-family: ${token.fontFamilyCode};
+ font-size: 12px;
+ `,
+ header: css`
+ .action-icon {
+ opacity: 0;
+ transition: opacity 0.2s ease;
+ }
+
+ &:hover {
+ .action-icon {
+ opacity: 1;
+ }
+ }
+ `,
+ statusIcon: css`
+ font-size: 12px;
+ `,
+}));
interface RunCommandProps {
args: RunCommandParams;
messageId: string;
pluginError: ChatMessagePluginError;
- pluginState: LocalReadFileState;
+ pluginState: {
+ message: string;
+ result: RunCommandResult;
+ };
}
-const RunCommand = memo<RunCommandProps>(({ args }) => {
- const terminalRef = useRef(null);
-
- useEffect(() => {
- if (!terminalRef.current) return;
-
- const term = new Terminal({ cols: 80, cursorBlink: true, rows: 30 });
-
- term.open(terminalRef.current);
- term.write(args.command);
+const RunCommand = memo<RunCommandProps>(({ args, pluginState }) => {
+ const { styles, theme } = useStyles();
+ const { result, message } = pluginState || {};
+ const isSuccess = result?.success;
+ const [expanded, setExpanded] = useState(false);
- return () => {
- term.dispose();
- };
- }, []);
+ return (
+ <Flexbox className={styles.container} gap={8}>
+ {/* Header: Description + Status */}
+ <Flexbox align={'center'} className={styles.header} horizontal justify={'space-between'}>
+ <Flexbox gap={8} horizontal>
+ <Flexbox gap={4} horizontal>
+ {!result ? null : isSuccess ? (
+ <CheckCircleFilled
+ className={styles.statusIcon}
+ style={{ color: theme.colorSuccess }}
+ />
+ ) : (
+ <CloseCircleFilled
+ className={styles.statusIcon}
+ style={{ color: theme.colorError }}
+ />
+ )}
+ {args.description && <Text className={styles.head}>{args.description}</Text>}
+ </Flexbox>
+ {message && (
+ <Flexbox align={'center'} gap={4} horizontal>
+ <Text className={styles.head} type={'secondary'}>
+ {message}
+ </Text>
+ </Flexbox>
+ )}
+ </Flexbox>
+ <Flexbox align={'center'} gap={8} horizontal>
+ <ActionIcon
+ className={`action-icon`}
+ icon={expanded ? ChevronUp : ChevronDown}
+ onClick={() => setExpanded(!expanded)}
+ size={'small'}
+ style={{ opacity: expanded ? 1 : undefined }}
+ title={expanded ? 'Collapse' : 'Expand'}
+ />
+ </Flexbox>
+ </Flexbox>
- return <div ref={terminalRef} />;
+ {/* Command & Output */}
+ {expanded && (
+ <Block gap={8} padding={8} variant={'outlined'}>
+ <Highlighter
+ language={'sh'}
+ showLanguage={false}
+ style={{ paddingInline: 8 }}
+ variant={'borderless'}
+ wrap
+ >
+ {args.command}
+ </Highlighter>
+ {result?.output && (
+ <Highlighter language={'text'} showLanguage={false} variant={'filled'} wrap>
+ {result.output}
+ </Highlighter>
+ )}
+ </Block>
+ )}
+ </Flexbox>
+ );
});
export default RunCommand;
diff --git a/src/tools/local-system/Render/index.tsx b/src/tools/local-system/Render/index.tsx
index 9ec23f0ce71..be579792cca 100644
--- a/src/tools/local-system/Render/index.tsx
+++ b/src/tools/local-system/Render/index.tsx
@@ -7,6 +7,7 @@ import { LocalSystemApiName } from '@/tools/local-system';
import ListFiles from './ListFiles';
import ReadLocalFile from './ReadLocalFile';
import RenameLocalFile from './RenameLocalFile';
+import RunCommand from './RunCommand';
import SearchFiles from './SearchFiles';
import WriteFile from './WriteFile';
@@ -16,6 +17,7 @@ const RenderMap = {
[LocalSystemApiName.readLocalFile]: ReadLocalFile,
[LocalSystemApiName.renameLocalFile]: RenameLocalFile,
[LocalSystemApiName.writeLocalFile]: WriteFile,
+ [LocalSystemApiName.runCommand]: RunCommand,
};
const LocalFilesRender = memo<BuiltinRenderProps<LocalFileItem[]>>(
diff --git a/src/tools/local-system/index.ts b/src/tools/local-system/index.ts
index dcd6c4d132e..21c39c29756 100644
--- a/src/tools/local-system/index.ts
+++ b/src/tools/local-system/index.ts
@@ -3,10 +3,16 @@ import { BuiltinToolManifest } from '@lobechat/types';
import { systemPrompt } from './systemRole';
export const LocalSystemApiName = {
+ editLocalFile: 'editLocalFile',
+ getCommandOutput: 'getCommandOutput',
+ globLocalFiles: 'globLocalFiles',
+ grepContent: 'grepContent',
+ killCommand: 'killCommand',
listLocalFiles: 'listLocalFiles',
moveLocalFiles: 'moveLocalFiles',
readLocalFile: 'readLocalFile',
renameLocalFile: 'renameLocalFile',
+ runCommand: 'runCommand',
searchLocalFiles: 'searchLocalFiles',
writeLocalFile: 'writeLocalFile',
};
@@ -130,6 +136,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {
{
description:
'Moves or renames multiple files/directories. Input is an array of objects, each containing an oldPath and a newPath.',
+ humanIntervention: 'required',
name: LocalSystemApiName.moveLocalFiles,
parameters: {
properties: {
@@ -195,6 +202,179 @@ export const LocalSystemManifest: BuiltinToolManifest = {
type: 'object',
},
},
+ {
+ description:
+ 'Execute a shell command and return its output. Supports both synchronous and background execution with timeout control.',
+ humanIntervention: 'required',
+ name: LocalSystemApiName.runCommand,
+ parameters: {
+ properties: {
+ command: {
+ description: 'The shell command to execute',
+ type: 'string',
+ },
+ description: {
+ description:
+ 'Clear description of what this command does (5-10 words, in active voice). Use the same language as the user input.',
+ type: 'string',
+ },
+ run_in_background: {
+ description: 'Set to true to run command in background and return shell_id',
+ type: 'boolean',
+ },
+ timeout: {
+ description: 'Timeout in milliseconds (default: 120000ms, max: 600000ms)',
+ type: 'number',
+ },
+ },
+ required: ['command'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Retrieve output from a running or completed background shell command. Returns only new output since the last check.',
+ name: LocalSystemApiName.getCommandOutput,
+ parameters: {
+ properties: {
+ filter: {
+ description:
+ 'Optional regex pattern to filter output lines. Only matching lines are returned.',
+ type: 'string',
+ },
+ shell_id: {
+ description: 'The ID of the background shell to retrieve output from',
+ type: 'string',
+ },
+ },
+ required: ['shell_id'],
+ type: 'object',
+ },
+ },
+ {
+ description: 'Kill a running background shell command by its ID.',
+ name: LocalSystemApiName.killCommand,
+ parameters: {
+ properties: {
+ shell_id: {
+ description: 'The ID of the background shell to kill',
+ type: 'string',
+ },
+ },
+ required: ['shell_id'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Search for content within files using regex patterns. Supports various output modes and filtering options.',
+ name: LocalSystemApiName.grepContent,
+ parameters: {
+ properties: {
+ '-A': {
+ description:
+ 'Number of lines to show after each match (requires output_mode: "content")',
+ type: 'number',
+ },
+ '-B': {
+ description:
+ 'Number of lines to show before each match (requires output_mode: "content")',
+ type: 'number',
+ },
+ '-C': {
+ description:
+ 'Number of lines to show before and after each match (requires output_mode: "content")',
+ type: 'number',
+ },
+ '-i': {
+ description: 'Case insensitive search',
+ type: 'boolean',
+ },
+ '-n': {
+ description: 'Show line numbers in output (requires output_mode: "content")',
+ type: 'boolean',
+ },
+ 'glob': {
+ description: 'Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}")',
+ type: 'string',
+ },
+ 'head_limit': {
+ description: 'Limit output to first N results',
+ type: 'number',
+ },
+ 'multiline': {
+ description: 'Enable multiline mode where . matches newlines',
+ type: 'boolean',
+ },
+ 'output_mode': {
+ description:
+ 'Output mode: "content" (matching lines), "files_with_matches" (file paths), "count" (match counts)',
+ enum: ['content', 'files_with_matches', 'count'],
+ type: 'string',
+ },
+ 'path': {
+ description: 'File or directory to search in (defaults to current working directory)',
+ type: 'string',
+ },
+ 'pattern': {
+ description: 'The regular expression pattern to search for',
+ type: 'string',
+ },
+ 'type': {
+ description: 'File type to search (e.g. "js", "py", "rust")',
+ type: 'string',
+ },
+ },
+ required: ['pattern'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Find files matching glob patterns. Supports standard glob syntax like "**/*.js" or "src/**/*.ts".',
+ name: LocalSystemApiName.globLocalFiles,
+ parameters: {
+ properties: {
+ path: {
+ description: 'The directory to search in (defaults to current working directory)',
+ type: 'string',
+ },
+ pattern: {
+ description: 'The glob pattern to match files against (e.g. "**/*.js", "*.{ts,tsx}")',
+ type: 'string',
+ },
+ },
+ required: ['pattern'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Perform exact string replacements in files. Must read the file first before editing.',
+ name: LocalSystemApiName.editLocalFile,
+ parameters: {
+ properties: {
+ file_path: {
+ description: 'The absolute path to the file to modify',
+ type: 'string',
+ },
+ new_string: {
+ description: 'The text to replace with (must differ from old_string)',
+ type: 'string',
+ },
+ old_string: {
+ description: 'The exact text to replace',
+ type: 'string',
+ },
+ replace_all: {
+ description: 'Replace all occurrences of old_string (default: false)',
+ type: 'boolean',
+ },
+ },
+ required: ['file_path', 'old_string', 'new_string'],
+ type: 'object',
+ },
+ },
],
identifier: 'lobe-local-system',
meta: {
diff --git a/src/tools/local-system/systemRole.ts b/src/tools/local-system/systemRole.ts
index 40b8fa1b23d..8e45e10e52b 100644
--- a/src/tools/local-system/systemRole.ts
+++ b/src/tools/local-system/systemRole.ts
@@ -15,19 +15,33 @@ Here are some known locations and system details on the user's system. User is u
<core_capabilities>
You have access to a set of tools to interact with the user's local file system:
+**File Operations:**
1. **listLocalFiles**: Lists files and directories in a specified path.
2. **readLocalFile**: Reads the content of a specified file, optionally within a line range. You can read file types such as Word, Excel, PowerPoint, PDF, and plain text files.
-3. **writeFile**: Write content to a specific file, only support plain text file like \`.text\` or \`.md\`
-4. **searchLocalFiles**: Searches for files based on keywords and other criteria. Use this tool to find files if the user is unsure about the exact path.
+3. **writeLocalFile**: Write content to a specific file, only support plain text file like \`.text\` or \`.md\`
+4. **searchLocalFiles**: Searches for files based on keywords and other criteria using Spotlight (macOS) or native search. Use this tool to find files if the user is unsure about the exact path.
5. **renameLocalFile**: Renames a single file or directory in its current location.
6. **moveLocalFiles**: Moves multiple files or directories. Can be used for renaming during the move.
+7. **editLocalFile**: Performs exact string replacements in files. Must read the file first before editing.
+
+**Shell Commands:**
+8. **runCommand**: Execute shell commands with timeout control. Supports both synchronous and background execution. When providing a description, always use the same language as the user's input.
+9. **getCommandOutput**: Retrieve output from running background commands. Returns only new output since last check.
+10. **killCommand**: Terminate a running background shell command by its ID.
+
+**Search & Find:**
+11. **grepContent**: Search for content within files using regex patterns. Supports various output modes, filtering, and context lines.
+12. **globLocalFiles**: Find files matching glob patterns (e.g., "**/*.js", "*.{ts,tsx}").
</core_capabilities>
<workflow>
-1. Understand the user's request regarding local files (listing, reading, searching, renaming, moving, writing).
-2. Select the appropriate tool (listFiles, readFile, searchFiles, renameFile, moveLocalFiles, writeFile).
-3. Execute the file operation. **If the user mentions a common location (like Desktop, Documents, Downloads, etc.) without providing a full path, use the corresponding path from the <user_context> section.**
-4. Present the results (directory listing, file content, search results) or confirmation of the rename or move operation.
+1. Understand the user's request regarding local operations (files, commands, searches).
+2. Select the appropriate tool:
+ - File operations: listLocalFiles, readLocalFile, writeLocalFile, editLocalFile, searchLocalFiles, renameLocalFile, moveLocalFiles
+ - Shell commands: runCommand, getCommandOutput, killCommand
+ - Search/Find: grepContent, globLocalFiles
+3. Execute the operation. **If the user mentions a common location (like Desktop, Documents, Downloads, etc.) without providing a full path, use the corresponding path from the <user_context> section.**
+4. Present the results or confirmation.
</workflow>
<tool_usage_guidelines>
@@ -54,7 +68,37 @@ You have access to a set of tools to interact with the user's local file system:
- 'oldPath': The current absolute path of the file/directory to move or rename.
- 'newPath': The target absolute path for the file/directory (can include a new name).
Example: items: [{ oldPath: "/path/to/file1.txt", newPath: "/new/path/to/fileA.txt" }, { oldPath: "/path/to/folderB", newPath: "/archive/folderB_renamed" }]
-- For writing to a file: Use 'writeFile' with the file path and the content to be written. Be cautious as this might overwrite existing files.
+- For writing to a file: Use 'writeLocalFile' with the file path and the content to be written. Be cautious as this might overwrite existing files.
+- For editing a file: Use 'editLocalFile'. Provide the following parameters:
+ - 'file_path': The absolute path to the file to modify.
+ - 'old_string': The exact text to replace.
+ - 'new_string': The text to replace with.
+ - 'replace_all' (Optional): Set to true to replace all occurrences (default: false, replaces only first occurrence).
+ Note: You MUST read the file first using 'readLocalFile' before editing to verify the content.
+- For executing shell commands: Use 'runCommand'. Provide the following parameters:
+ - 'command': The shell command to execute.
+ - 'description' (Optional but recommended): A clear, concise description of what the command does (5-10 words, in active voice). **IMPORTANT: Always use the same language as the user's input.** If the user speaks Chinese, write the description in Chinese; if English, use English, etc.
+ - 'run_in_background' (Optional): Set to true to run in background and get a shell_id for later checking output.
+ - 'timeout' (Optional): Timeout in milliseconds (default: 120000ms, max: 600000ms).
+ The command runs in cmd.exe on Windows or /bin/sh on macOS/Linux.
+- For retrieving output from background commands: Use 'getCommandOutput'. Provide:
+ - 'shell_id': The ID returned from runCommand when run_in_background was true.
+ - 'filter' (Optional): A regex pattern to filter output lines.
+ Returns only new output since the last check.
+- For killing background commands: Use 'killCommand' with 'shell_id'.
+- For searching content in files: Use 'grepContent'. Provide:
+ - 'pattern': The regex pattern to search for.
+ - 'path' (Optional): File or directory to search (defaults to current working directory).
+ - 'output_mode' (Optional): "content" (matching lines), "files_with_matches" (file paths, default), "count" (match counts).
+ - 'glob' (Optional): Glob pattern to filter files (e.g., "*.js", "*.{ts,tsx}").
+ - '-i' (Optional): Case insensitive search.
+ - '-n' (Optional): Show line numbers (requires output_mode: "content").
+ - '-A/-B/-C' (Optional): Show N lines after/before/around matches (requires output_mode: "content").
+ - 'head_limit' (Optional): Limit results to first N matches.
+- For finding files by pattern: Use 'globLocalFiles'. Provide:
+ - 'pattern': Glob pattern (e.g., "**/*.js", "src/**/*.ts").
+ - 'path' (Optional): Directory to search in (defaults to current working directory).
+ Returns files sorted by modification time (most recent first).
</tool_usage_guidelines>
<security_considerations>
@@ -62,6 +106,16 @@ You have access to a set of tools to interact with the user's local file system:
- Confirm with the user before moving files to significantly different locations or when renaming might cause confusion or potential data loss if the target exists (though the tool should handle this).
- Do not attempt to access files outside the user's designated workspace or allowed directories unless explicitly permitted.
- Handle file paths carefully to avoid unintended access or errors.
+- When running shell commands:
+ - Never execute commands that could harm the system or delete important data without explicit user confirmation.
+ - Be cautious with commands that have side effects (e.g., rm, sudo, format).
+ - Always describe what a command will do before running it, especially for non-trivial operations.
+ - Always provide a clear 'description' parameter in the user's language to help them understand what the command does.
+ - Use appropriate timeouts to prevent commands from running indefinitely.
+- When editing files:
+ - Always read the file first to verify its current content.
+ - Ensure old_string exactly matches the text to be replaced to avoid unintended changes.
+ - Be cautious when using replace_all option.
</security_considerations>
<response_format>