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.

update

Inneia33cf6c8c61b
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
index 09f6e52b796..ff272968646 100644
--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import type { App } from '@/core/App';
+import { type App } from '@/core/App';
import LocalFileCtr from '../LocalFileCtr';
@@ -408,7 +408,7 @@ describe('LocalFileCtr', () => {
const result = await localFileCtr.handleGlobFiles({
pattern: '*.txt',
- path: '/test',
+ scope: '/test',
});
expect(result.success).toBe(true);
@@ -416,7 +416,7 @@ describe('LocalFileCtr', () => {
expect(result.total_files).toBe(2);
expect(mockSearchService.glob).toHaveBeenCalledWith({
pattern: '*.txt',
- path: '/test',
+ scope: '/test',
});
});
diff --git a/apps/desktop/src/main/modules/fileSearch/impl/unix.ts b/apps/desktop/src/main/modules/fileSearch/impl/unix.ts
index c9ba13e39cd..3fa35ad2486 100644
--- a/apps/desktop/src/main/modules/fileSearch/impl/unix.ts
+++ b/apps/desktop/src/main/modules/fileSearch/impl/unix.ts
@@ -1,16 +1,17 @@
-/* eslint-disable unicorn/no-array-push-push */
-import { GlobFilesParams, GlobFilesResult } from '@lobechat/electron-client-ipc';
-import { execa } from 'execa';
-import fg from 'fast-glob';
-import { Stats } from 'node:fs';
+
+import { type Stats } from 'node:fs';
import { stat } from 'node:fs/promises';
import * as os from 'node:os';
-import { ToolDetectorManager } from '@/core/infrastructure/ToolDetectorManager';
+import { type GlobFilesParams, type GlobFilesResult } from '@lobechat/electron-client-ipc';
+import { execa } from 'execa';
+import fg from 'fast-glob';
+
+import { type ToolDetectorManager } from '@/core/infrastructure/ToolDetectorManager';
import { createLogger } from '@/utils/logger';
import { BaseFileSearch } from '../base';
-import { FileResult, SearchOptions } from '../types';
+import { type FileResult, type SearchOptions } from '../types';
const logger = createLogger('module:FileSearch:unix');
@@ -190,10 +191,7 @@ export abstract class UnixFileSearch extends BaseFileSearch {
logger.debug('Performing find search', { keywords: options.keywords, searchDir });
try {
- const args: string[] = [searchDir];
-
- // Limit depth and exclude common directories
- args.push(
+ const args: string[] = [searchDir,
'-maxdepth',
'10',
'-type',
@@ -209,8 +207,9 @@ export abstract class UnixFileSearch extends BaseFileSearch {
'*/*cache*/*',
')',
'-prune',
- '-o',
- );
+ '-o'];
+
+ // Limit depth and exclude common directories
// Pattern matching
if (options.keywords) {
@@ -337,7 +336,7 @@ export abstract class UnixFileSearch extends BaseFileSearch {
* @returns Glob results
*/
protected async globWithFd(params: GlobFilesParams): Promise<GlobFilesResult> {
- const searchPath = params.path || process.cwd();
+ const searchPath = params.scope || process.cwd();
const logPrefix = `[glob:fd: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting fd glob`, { searchPath });
@@ -393,7 +392,7 @@ export abstract class UnixFileSearch extends BaseFileSearch {
* @returns Glob results
*/
protected async globWithFind(params: GlobFilesParams): Promise<GlobFilesResult> {
- const searchPath = params.path || process.cwd();
+ const searchPath = params.scope || process.cwd();
const logPrefix = `[glob:find: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting find glob`, { searchPath });
@@ -455,7 +454,7 @@ export abstract class UnixFileSearch extends BaseFileSearch {
* @returns Glob results
*/
protected async globWithFastGlob(params: GlobFilesParams): Promise<GlobFilesResult> {
- const searchPath = params.path || process.cwd();
+ const searchPath = params.scope || process.cwd();
const logPrefix = `[glob:fast-glob: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting fast-glob`, { searchPath });
diff --git a/apps/desktop/src/main/modules/fileSearch/impl/windows.ts b/apps/desktop/src/main/modules/fileSearch/impl/windows.ts
index 8b21e3b7f7c..adbd2b1ca7e 100644
--- a/apps/desktop/src/main/modules/fileSearch/impl/windows.ts
+++ b/apps/desktop/src/main/modules/fileSearch/impl/windows.ts
@@ -1,16 +1,17 @@
-/* eslint-disable unicorn/no-array-push-push */
-import { GlobFilesParams, GlobFilesResult } from '@lobechat/electron-client-ipc';
-import { execa } from 'execa';
-import fg from 'fast-glob';
-import { Stats } from 'node:fs';
+
+import { type Stats } from 'node:fs';
import { stat } from 'node:fs/promises';
import * as os from 'node:os';
-import { ToolDetectorManager } from '@/core/infrastructure/ToolDetectorManager';
+import { type GlobFilesParams, type GlobFilesResult } from '@lobechat/electron-client-ipc';
+import { execa } from 'execa';
+import fg from 'fast-glob';
+
+import { type ToolDetectorManager } from '@/core/infrastructure/ToolDetectorManager';
import { createLogger } from '@/utils/logger';
import { BaseFileSearch } from '../base';
-import { FileResult, SearchOptions } from '../types';
+import { type FileResult, type SearchOptions } from '../types';
const logger = createLogger('module:FileSearch:windows');
@@ -335,7 +336,7 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
* @returns Glob results
*/
private async globWithFd(params: GlobFilesParams): Promise<GlobFilesResult> {
- const searchPath = params.path || process.cwd();
+ const searchPath = params.scope || process.cwd();
const logPrefix = `[glob:fd: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting fd glob`, { searchPath });
@@ -390,7 +391,7 @@ export class WindowsSearchServiceImpl extends BaseFileSearch {
* @returns Glob results
*/
private async globWithFastGlob(params: GlobFilesParams): Promise<GlobFilesResult> {
- const searchPath = params.path || process.cwd();
+ const searchPath = params.scope || process.cwd();
const logPrefix = `[glob:fast-glob: ${params.pattern}]`;
logger.debug(`${logPrefix} Starting fast-glob`, { searchPath });
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index c5cd8abad8a..4fdd23a4d0a 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -523,12 +523,6 @@
"src/store/chat/slices/aiChat/actions/streamingExecutor.ts": {
"no-unused-private-class-members": {
"count": 1
- },
- "sort-keys-fix/sort-keys-fix": {
- "count": 1
- },
- "typescript-sort-keys/interface": {
- "count": 1
}
},
"src/store/chat/slices/message/actions/optimisticUpdate.ts": {
diff --git a/locales/en-US/tool.json b/locales/en-US/tool.json
index c1232973f79..755f3aeaddb 100644
--- a/locales/en-US/tool.json
+++ b/locales/en-US/tool.json
@@ -100,6 +100,7 @@
"localFiles.readFileError": "Failed to read file, please check if the file path is correct",
"localFiles.readFiles": "Read Files",
"localFiles.readFilesError": "Failed to read files, please check if the file path is correct",
+ "localFiles.securityBlacklist.warning": "Security Alert: This operation has been flagged by security rules and requires your explicit approval.",
"localFiles.writeFile.characters": "characters",
"localFiles.writeFile.preview": "Content Preview",
"localFiles.writeFile.truncated": "truncated",
@@ -136,6 +137,31 @@
"search.summary": "Summary",
"search.summaryTooltip": "Summarize the current content",
"search.viewMoreResults": "View {{results}} more results",
+ "securityBlacklist.awsCredentials": "Accessing AWS credentials can leak cloud access keys",
+ "securityBlacklist.browserCredentials": "Accessing browser credential storage may leak passwords",
+ "securityBlacklist.chownSystemDirs": "Changing file ownership of system directories is dangerous",
+ "securityBlacklist.ddDiskWrite": "Writing random data to disk devices can destroy data",
+ "securityBlacklist.directMemoryAccess": "Direct memory access is extremely dangerous",
+ "securityBlacklist.disableFirewall": "Disabling firewall exposes system to attacks",
+ "securityBlacklist.dockerConfig": "Reading Docker config may expose registry credentials",
+ "securityBlacklist.envFiles": "Reading .env files may leak sensitive credentials and API keys",
+ "securityBlacklist.etcPasswd": "Modifying /etc/passwd could lock you out of the system",
+ "securityBlacklist.forkBomb": "Fork bomb can crash the system",
+ "securityBlacklist.formatPartition": "Formatting system partitions will destroy data",
+ "securityBlacklist.gcpCredentials": "Reading GCP credentials may leak cloud service account keys",
+ "securityBlacklist.gitCredentials": "Reading Git credentials file may leak access tokens",
+ "securityBlacklist.historyFiles": "Reading history files may expose sensitive commands and credentials",
+ "securityBlacklist.kernelParams": "Modifying kernel parameters without understanding can crash the system",
+ "securityBlacklist.kubeConfig": "Reading Kubernetes config may expose cluster credentials",
+ "securityBlacklist.npmrc": "Reading npm token file may expose package registry credentials",
+ "securityBlacklist.removeSystemPackages": "Removing essential system packages can break the system",
+ "securityBlacklist.rmForceRecursive": "Force recursive deletion without specific target is too dangerous",
+ "securityBlacklist.rmHomeDir": "Recursive deletion of home directory is extremely dangerous",
+ "securityBlacklist.rmRootDir": "Recursive deletion of root directory will destroy the system",
+ "securityBlacklist.sshConfig": "Changing SSH configuration could lock you out",
+ "securityBlacklist.sshPrivateKeys": "Reading SSH private keys can compromise system security",
+ "securityBlacklist.sudoers": "Modifying sudoers file without proper validation is dangerous",
+ "securityBlacklist.suidShells": "Setting SUID on shells or interpreters is a security risk",
"updateArgs.duplicateKeyError": "Field key must be unique",
"updateArgs.form.add": "Add an Item",
"updateArgs.form.key": "Field Key",
diff --git a/locales/zh-CN/tool.json b/locales/zh-CN/tool.json
index 587975d2ec8..d2e9fa2e353 100644
--- a/locales/zh-CN/tool.json
+++ b/locales/zh-CN/tool.json
@@ -100,6 +100,7 @@
"localFiles.readFileError": "读取文件失败,请检查文件路径是否正确",
"localFiles.readFiles": "读取多个文件",
"localFiles.readFilesError": "读取文件失败,请检查文件路径是否正确",
+ "localFiles.securityBlacklist.warning": "安全警告:此操作已被安全规则标记,需要您的明确批准。",
"localFiles.writeFile.characters": "字符",
"localFiles.writeFile.preview": "内容预览",
"localFiles.writeFile.truncated": "已截断",
@@ -136,6 +137,31 @@
"search.summary": "摘要",
"search.summaryTooltip": "总结当前内容",
"search.viewMoreResults": "查看更多 {{results}} 个结果",
+ "securityBlacklist.awsCredentials": "访问 AWS 凭证可能泄露云访问密钥",
+ "securityBlacklist.browserCredentials": "访问浏览器凭证存储可能泄露密码",
+ "securityBlacklist.chownSystemDirs": "更改系统目录的文件所有权是危险操作",
+ "securityBlacklist.ddDiskWrite": "向磁盘设备写入随机数据可能导致数据丢失",
+ "securityBlacklist.directMemoryAccess": "直接内存访问极其危险",
+ "securityBlacklist.disableFirewall": "禁用防火墙会使系统暴露于攻击之下",
+ "securityBlacklist.dockerConfig": "读取 Docker 配置可能泄露镜像仓库凭证",
+ "securityBlacklist.envFiles": "读取 .env 文件可能泄露敏感凭证和 API 密钥",
+ "securityBlacklist.etcPasswd": "修改 /etc/passwd 可能导致系统无法登录",
+ "securityBlacklist.forkBomb": "Fork 炸弹可能导致系统崩溃",
+ "securityBlacklist.formatPartition": "格式化系统分区将导致数据丢失",
+ "securityBlacklist.gcpCredentials": "读取 GCP 凭证可能泄露云服务账户密钥",
+ "securityBlacklist.gitCredentials": "读取 Git 凭证文件可能泄露访问令牌",
+ "securityBlacklist.historyFiles": "读取历史文件可能泄露敏感命令和凭证",
+ "securityBlacklist.kernelParams": "在不了解的情况下修改内核参数可能导致系统崩溃",
+ "securityBlacklist.kubeConfig": "读取 Kubernetes 配置可能泄露集群凭证",
+ "securityBlacklist.npmrc": "读取 npm token 文件可能泄露包注册表凭证",
+ "securityBlacklist.removeSystemPackages": "移除关键系统软件包可能导致系统损坏",
+ "securityBlacklist.rmForceRecursive": "未指定目标的强制递归删除过于危险",
+ "securityBlacklist.rmHomeDir": "递归删除主目录极其危险",
+ "securityBlacklist.rmRootDir": "递归删除根目录将摧毁整个系统",
+ "securityBlacklist.sshConfig": "更改 SSH 配置可能导致无法远程登录",
+ "securityBlacklist.sshPrivateKeys": "读取 SSH 私钥可能危及系统安全",
+ "securityBlacklist.sudoers": "未经正确验证修改 sudoers 文件是危险操作",
+ "securityBlacklist.suidShells": "在 Shell 或解释器上设置 SUID 是安全风险",
"updateArgs.duplicateKeyError": "字段键必须唯一",
"updateArgs.form.add": "添加一项",
"updateArgs.form.key": "字段键",
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
index 5fd9a7e0a6c..d90808fa49f 100644
--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts
+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
@@ -1,22 +1,28 @@
-import type { ChatToolPayload, HumanInterventionConfig } from '@lobechat/types';
-
-import { DEFAULT_SECURITY_BLACKLIST, InterventionChecker } from '../core';
-import type {
- Agent,
- AgentInstruction,
- AgentInstructionCompressContext,
- AgentRuntimeContext,
- AgentState,
- GeneralAgentCallingToolInstructionPayload,
- GeneralAgentCallLLMInstructionPayload,
- GeneralAgentCallLLMResultPayload,
- GeneralAgentCallToolResultPayload,
- GeneralAgentCallToolsBatchInstructionPayload,
- GeneralAgentCompressionResultPayload,
- GeneralAgentConfig,
- HumanAbortPayload,
- TaskResultPayload,
- TasksBatchResultPayload,
+import {
+ type ChatToolPayload,
+ type ExtendedHumanInterventionConfig,
+ type HumanInterventionConfig,
+ type HumanInterventionPolicy,
+} from '@lobechat/types';
+
+import { createDefaultGlobalAudits, DEFAULT_SECURITY_BLACKLIST } from '../audit';
+import { InterventionChecker } from '../core';
+import {
+ type Agent,
+ type AgentInstruction,
+ type AgentInstructionCompressContext,
+ type AgentRuntimeContext,
+ type AgentState,
+ type GeneralAgentCallingToolInstructionPayload,
+ type GeneralAgentCallLLMInstructionPayload,
+ type GeneralAgentCallLLMResultPayload,
+ type GeneralAgentCallToolResultPayload,
+ type GeneralAgentCallToolsBatchInstructionPayload,
+ type GeneralAgentCompressionResultPayload,
+ type GeneralAgentConfig,
+ type HumanAbortPayload,
+ type TaskResultPayload,
+ type TasksBatchResultPayload,
} from '../types';
import { shouldCompress } from '../utils/tokenCounter';
@@ -46,7 +52,7 @@ export class GeneralChatAgent implements Agent {
private getToolInterventionConfig(
toolCalling: ChatToolPayload,
state: AgentState,
- ): HumanInterventionConfig | undefined {
+ ): ExtendedHumanInterventionConfig | undefined {
const { identifier, apiName } = toolCalling;
const manifest = state.toolManifestMap[identifier];
@@ -59,6 +65,57 @@ export class GeneralChatAgent implements Agent {
return api?.humanIntervention ?? manifest.humanIntervention;
}
+ private isDynamicInterventionConfig(
+ config: ExtendedHumanInterventionConfig | undefined,
+ ): config is {
+ dynamic: { default?: HumanInterventionPolicy; policy?: HumanInterventionPolicy; type: string };
+ } {
+ return !!config && typeof config === 'object' && !Array.isArray(config) && 'dynamic' in config;
+ }
+
+ private matchesAlwaysPolicy(
+ config: HumanInterventionConfig | undefined,
+ toolArgs: Record<string, any>,
+ ): boolean {
+ if (!config) return false;
+ if (config === 'always') return true;
+ if (!Array.isArray(config)) return false;
+
+ return config.some((rule) => {
+ if (rule.policy !== 'always') return false;
+ if (!rule.match) return true;
+
+ return Object.entries(rule.match).every(([paramName, matcher]) => {
+ const paramValue = toolArgs[paramName];
+ if (paramValue === undefined) return false;
+
+ if (typeof matcher === 'string') {
+ return String(paramValue).includes(matcher) || matcher.includes('*');
+ }
+
+ return true;
+ });
+ });
+ }
+
+ private resolveDynamicPolicy(
+ config: ExtendedHumanInterventionConfig | undefined,
+ toolArgs: Record<string, any>,
+ metadata?: Record<string, any>,
+ ): HumanInterventionPolicy | undefined {
+ if (!this.isDynamicInterventionConfig(config)) {
+ return undefined;
+ }
+
+ const { dynamic } = config;
+ const resolver = this.config.dynamicInterventionAudits?.[dynamic.type];
+
+ if (!resolver) return dynamic.default ?? 'never';
+
+ const shouldIntervene = resolver(toolArgs, metadata);
+ return shouldIntervene ? (dynamic.policy ?? 'always') : (dynamic.default ?? 'never');
+ }
+
/**
* Check if tool calls need human intervention
* Combines user's global config with tool's own config
@@ -71,13 +128,19 @@ export class GeneralChatAgent implements Agent {
const toolsNeedingIntervention: ChatToolPayload[] = [];
const toolsToExecute: ChatToolPayload[] = [];
- // Get security blacklist (use default if not provided)
+ // Get security blacklist for resolver metadata
const securityBlacklist = state.securityBlacklist ?? DEFAULT_SECURITY_BLACKLIST;
+ // Build resolver metadata: merge state.metadata with security blacklist
+ const resolverMetadata = { ...state.metadata, securityBlacklist };
+
// Get user config (default to 'manual' mode)
const userConfig = state.userInterventionConfig || { approvalMode: 'manual' };
const { approvalMode, allowList = [] } = userConfig;
+ // Global audits: default to security blacklist audit if not provided
+ const globalResolvers = this.config.globalInterventionAudits ?? createDefaultGlobalAudits();
+
for (const toolCalling of toolsCalling) {
const { identifier, apiName } = toolCalling;
const toolKey = `${identifier}/${apiName}`;
@@ -90,64 +153,71 @@ export class GeneralChatAgent implements Agent {
// Invalid JSON, treat as empty args
}
- // Priority 0: CRITICAL - Check security blacklist FIRST
- const securityCheck = InterventionChecker.checkSecurityBlacklist(securityBlacklist, toolArgs);
+ // Phase 1: Run global resolvers (e.g., security blacklist)
+ let globalBlocked = false;
+ let globalPolicy: HumanInterventionPolicy = 'always';
+
+ for (const globalResolver of globalResolvers) {
+ if (globalResolver.resolver(toolArgs, resolverMetadata)) {
+ globalBlocked = true;
+ globalPolicy = globalResolver.policy ?? 'always';
+ break;
+ }
+ }
- // Priority 0.5: Headless mode - fully automated for async tasks
- // In headless mode: blacklisted tools are skipped, all other tools execute directly
+ // Phase 2: Headless mode - fully automated for async tasks
if (approvalMode === 'headless') {
- if (securityCheck.blocked) {
- // Skip blacklisted tools entirely (don't execute, don't wait for approval)
+ if (globalBlocked && globalPolicy === 'always') {
+ // Skip 'always' blocked tools entirely (don't execute, don't wait for approval)
continue;
}
- // All other tools execute directly
+ // All other tools execute directly (including overridable global blocks)
toolsToExecute.push(toolCalling);
continue;
}
- // For non-headless modes: security blacklist requires intervention
- if (securityCheck.blocked) {
+ // For non-headless modes: 'always' global block requires intervention unconditionally
+ if (globalBlocked && globalPolicy === 'always') {
toolsNeedingIntervention.push(toolCalling);
continue;
}
- // Priority 1: Check 'always' policy - overrides auto-run mode
- // Some sensitive operations (e.g., installPlugin) must always require user confirmation
+ // Phase 3: Per-tool dynamic resolver
const config = this.getToolInterventionConfig(toolCalling, state);
- const hasAlwaysPolicy =
- config === 'always' ||
- (Array.isArray(config) &&
- config.some((rule) => {
- // Check if the 'always' rule matches current tool args
- if (rule.policy !== 'always') return false;
- // If rule has match criteria, check if it matches
- if (rule.match) {
- return Object.entries(rule.match).every(([paramName, matcher]) => {
- const paramValue = toolArgs[paramName];
- if (paramValue === undefined) return false;
- // Simple string comparison for basic matching
- if (typeof matcher === 'string') {
- return String(paramValue).includes(matcher) || matcher.includes('*');
- }
- return true;
- });
- }
- // No match criteria means it's a default 'always' rule
- return true;
- }));
+ const isDynamicConfig = this.isDynamicInterventionConfig(config);
+ const dynamicPolicy = this.resolveDynamicPolicy(config, toolArgs, state.metadata);
+ const staticConfig = isDynamicConfig
+ ? undefined
+ : (config as HumanInterventionConfig | undefined);
+
+ if (dynamicPolicy !== undefined) {
+ if (dynamicPolicy === 'never') {
+ toolsToExecute.push(toolCalling);
+ } else {
+ toolsNeedingIntervention.push(toolCalling);
+ }
+ continue;
+ }
+
+ // Phase 3.5: Handle overridable global block (policy !== 'always')
+ if (globalBlocked && globalPolicy !== 'always') {
+ toolsNeedingIntervention.push(toolCalling);
+ continue;
+ }
- if (hasAlwaysPolicy) {
+ // Phase 4: Check 'always' policy - overrides auto-run mode
+ if (this.matchesAlwaysPolicy(staticConfig, toolArgs)) {
toolsNeedingIntervention.push(toolCalling);
continue;
}
- // Priority 2: User config is 'auto-run', all tools execute directly
+ // Phase 5: User config is 'auto-run', all tools execute directly
if (approvalMode === 'auto-run') {
toolsToExecute.push(toolCalling);
continue;
}
- // Priority 3: User config is 'allow-list', check if tool is in whitelist
+ // Phase 6: User config is 'allow-list', check if tool is in whitelist
if (approvalMode === 'allow-list') {
if (allowList.includes(toolKey)) {
toolsToExecute.push(toolCalling);
@@ -157,10 +227,9 @@ export class GeneralChatAgent implements Agent {
continue;
}
- // Priority 4: User config is 'manual' (default), use tool's own config
- // Note: config is already retrieved above for 'always' policy check
+ // Phase 7: User config is 'manual' (default), use tool's own config
const policy = InterventionChecker.shouldIntervene({
- config,
+ config: staticConfig,
securityBlacklist,
toolArgs,
});
@@ -168,7 +237,6 @@ export class GeneralChatAgent implements Agent {
if (policy === 'never') {
toolsToExecute.push(toolCalling);
} else {
- // 'required' or undefined requires intervention
toolsNeedingIntervention.push(toolCalling);
}
}
diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
index 958996ae32b..e6640d8196e 100644
--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
@@ -1,7 +1,7 @@
-import type { ChatToolPayload } from '@lobechat/types';
+import { type ChatToolPayload, type GlobalInterventionAuditConfig } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import type { AgentRuntimeContext, AgentState } from '../../types';
+import { type AgentRuntimeContext, type AgentState } from '../../types';
import { GeneralChatAgent } from '../GeneralChatAgent';
describe('GeneralChatAgent', () => {
@@ -1302,6 +1302,130 @@ describe('GeneralChatAgent', () => {
});
describe('intervention checking', () => {
+ it('should require intervention when dynamic policy resolves to required', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ dynamicInterventionAudits: {
+ pathScopeAudit: (toolArgs, metadata) => {
+ const workingDirectory = metadata?.workingDirectory as string | undefined;
+ if (!workingDirectory) return false;
+ const path = toolArgs.path as string;
+ return !path.startsWith(workingDirectory);
+ },
+ },
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const toolCall: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'local-system',
+ apiName: 'readLocalFile',
+ arguments: '{"path":"/etc/passwd"}',
+ type: 'builtin',
+ };
+
+ const state = createMockState({
+ metadata: { workingDirectory: '/workspace' },
+ toolManifestMap: {
+ 'local-system': {
+ identifier: 'local-system',
+ api: [
+ {
+ name: 'readLocalFile',
+ humanIntervention: {
+ dynamic: {
+ default: 'never',
+ policy: 'required',
+ type: 'pathScopeAudit',
+ },
+ },
+ },
+ ],
+ },
+ },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual([
+ {
+ type: 'request_human_approve',
+ pendingToolsCalling: [toolCall],
+ reason: 'human_intervention_required',
+ },
+ ]);
+ });
+
+ it('should execute tool when dynamic policy resolves to never', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ dynamicInterventionAudits: {
+ pathScopeAudit: (toolArgs, metadata) => {
+ const workingDirectory = metadata?.workingDirectory as string | undefined;
+ if (!workingDirectory) return false;
+ const path = toolArgs.path as string;
+ return !path.startsWith(workingDirectory);
+ },
+ },
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const toolCall: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'local-system',
+ apiName: 'readLocalFile',
+ arguments: '{"path":"/workspace/README.md"}',
+ type: 'builtin',
+ };
+
+ const state = createMockState({
+ metadata: { workingDirectory: '/workspace' },
+ toolManifestMap: {
+ 'local-system': {
+ identifier: 'local-system',
+ api: [
+ {
+ name: 'readLocalFile',
+ humanIntervention: {
+ dynamic: {
+ default: 'never',
+ policy: 'required',
+ type: 'pathScopeAudit',
+ },
+ },
+ },
+ ],
+ },
+ },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual([
+ {
+ type: 'call_tool',
+ payload: {
+ parentMessageId: 'msg-1',
+ toolCalling: toolCall,
+ },
+ },
+ ]);
+ });
+
it('should check intervention at API level when configured', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
@@ -1749,6 +1873,372 @@ describe('GeneralChatAgent', () => {
});
});
+ describe('global intervention resolvers', () => {
+ it('should use custom global resolver with policy always to block tools', async () => {
+ const customResolver: GlobalInterventionAuditConfig = {
+ type: 'customBlocker',
+ policy: 'always',
+ resolver: (toolArgs) => toolArgs.dangerous === true,
+ };
+
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ globalInterventionAudits: [customResolver],
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const toolCall: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'my-tool',
+ apiName: 'doSomething',
+ arguments: '{"dangerous":true}',
+ type: 'default',
+ };
+
+ const state = createMockState({
+ toolManifestMap: {
+ 'my-tool': { identifier: 'my-tool', humanIntervention: 'never' },
+ },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual([
+ {
+ type: 'request_human_approve',
+ pendingToolsCalling: [toolCall],
+ reason: 'human_intervention_required',
+ },
+ ]);
+ });
+
+ it('should allow tool execution when global resolver does not trigger', async () => {
+ const customResolver: GlobalInterventionAuditConfig = {
+ type: 'customBlocker',
+ policy: 'always',
+ resolver: (toolArgs) => toolArgs.dangerous === true,
+ };
+
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ globalInterventionAudits: [customResolver],
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const toolCall: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'my-tool',
+ apiName: 'doSomething',
+ arguments: '{"dangerous":false}',
+ type: 'default',
+ };
+
+ const state = createMockState({
+ toolManifestMap: {
+ 'my-tool': { identifier: 'my-tool', humanIntervention: 'never' },
+ },
+ userInterventionConfig: { approvalMode: 'auto-run' },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual([
+ {
+ type: 'call_tool',
+ payload: { parentMessageId: 'msg-1', toolCalling: toolCall },
+ },
+ ]);
+ });
+
+ it('should skip tool in headless mode when global resolver with policy always triggers', async () => {
+ const customResolver: GlobalInterventionAuditConfig = {
+ type: 'customBlocker',
+ policy: 'always',
+ resolver: (toolArgs) => toolArgs.blocked === true,
+ };
+
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ globalInterventionAudits: [customResolver],
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const blockedTool: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'my-tool',
+ apiName: 'doSomething',
+ arguments: '{"blocked":true}',
+ type: 'default',
+ };
+
+ const state = createMockState({
+ toolManifestMap: {
+ 'my-tool': { identifier: 'my-tool' },
+ },
+ userInterventionConfig: { approvalMode: 'headless' },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [blockedTool],
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ // Tool is skipped entirely in headless mode with 'always' policy
+ expect(result).toEqual([]);
+ });
+
+ it('should execute tool in headless mode when global resolver with policy required triggers', async () => {
+ const customResolver: GlobalInterventionAuditConfig = {
+ type: 'softBlocker',
+ policy: 'required',
+ resolver: () => true, // always triggers
+ };
+
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ globalInterventionAudits: [customResolver],
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const toolCall: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'my-tool',
+ apiName: 'doSomething',
+ arguments: '{}',
+ type: 'default',
+ };
+
+ const state = createMockState({
+ toolManifestMap: {
+ 'my-tool': { identifier: 'my-tool' },
+ },
+ userInterventionConfig: { approvalMode: 'headless' },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ // 'required' policy is overridable → headless mode executes directly
+ expect(result).toEqual([
+ {
+ type: 'call_tool',
+ payload: { parentMessageId: 'msg-1', toolCalling: toolCall },
+ },
+ ]);
+ });
+
+ it('should require intervention for overridable global resolver in non-headless mode', async () => {
+ const customResolver: GlobalInterventionAuditConfig = {
+ type: 'softBlocker',
+ policy: 'required',
+ resolver: () => true,
+ };
+
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ globalInterventionAudits: [customResolver],
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const toolCall: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'my-tool',
+ apiName: 'doSomething',
+ arguments: '{}',
+ type: 'default',
+ };
+
+ const state = createMockState({
+ toolManifestMap: {
+ 'my-tool': { identifier: 'my-tool', humanIntervention: 'never' },
+ },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual([
+ {
+ type: 'request_human_approve',
+ pendingToolsCalling: [toolCall],
+ reason: 'human_intervention_required',
+ },
+ ]);
+ });
+
+ it('should pass resolver metadata including securityBlacklist to global resolvers', async () => {
+ let capturedMetadata: Record<string, any> | undefined;
+
+ const spyResolver: GlobalInterventionAuditConfig = {
+ type: 'spy',
+ policy: 'always',
+ resolver: (_toolArgs, metadata) => {
+ capturedMetadata = metadata;
+ return false;
+ },
+ };
+
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ globalInterventionAudits: [spyResolver],
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const toolCall: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'my-tool',
+ apiName: 'doSomething',
+ arguments: '{}',
+ type: 'default',
+ };
+
+ const state = createMockState({
+ metadata: { workingDirectory: '/workspace' },
+ toolManifestMap: {
+ 'my-tool': { identifier: 'my-tool', humanIntervention: 'never' },
+ },
+ userInterventionConfig: { approvalMode: 'auto-run' },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: 'msg-1',
+ });
+
+ await agent.runner(context, state);
+
+ // Resolver should receive metadata with securityBlacklist merged in
+ expect(capturedMetadata).toBeDefined();
+ expect(capturedMetadata!.workingDirectory).toBe('/workspace');
+ expect(capturedMetadata!.securityBlacklist).toBeDefined();
+ expect(Array.isArray(capturedMetadata!.securityBlacklist)).toBe(true);
+ });
+
+ it('should evaluate global resolvers in array order and stop at first match', async () => {
+ const callOrder: string[] = [];
+
+ const resolver1: GlobalInterventionAuditConfig = {
+ type: 'first',
+ policy: 'always',
+ resolver: () => {
+ callOrder.push('first');
+ return true; // matches
+ },
+ };
+
+ const resolver2: GlobalInterventionAuditConfig = {
+ type: 'second',
+ policy: 'required',
+ resolver: () => {
+ callOrder.push('second');
+ return true;
+ },
+ };
+
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ globalInterventionAudits: [resolver1, resolver2],
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const toolCall: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'my-tool',
+ apiName: 'doSomething',
+ arguments: '{}',
+ type: 'default',
+ };
+
+ const state = createMockState({
+ toolManifestMap: { 'my-tool': { identifier: 'my-tool' } },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: 'msg-1',
+ });
+
+ await agent.runner(context, state);
+
+ // Only first resolver should be called (break on first match)
+ expect(callOrder).toEqual(['first']);
+ });
+
+ it('should use default security blacklist audit when globalInterventionAudits is not provided', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ // NOT providing globalInterventionAudits → should default to security blacklist
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const blacklistedTool: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'bash',
+ apiName: 'bash',
+ arguments: '{"command":"rm -rf /"}',
+ type: 'builtin',
+ };
+
+ const state = createMockState({
+ toolManifestMap: {
+ bash: { identifier: 'bash', humanIntervention: 'never' },
+ },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [blacklistedTool],
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ // Default global resolver (security blacklist) should catch this
+ expect(result).toEqual([
+ {
+ type: 'request_human_approve',
+ pendingToolsCalling: [blacklistedTool],
+ reason: 'human_intervention_required',
+ },
+ ]);
+ });
+ });
+
describe('headless mode (for async tasks)', () => {
it('should execute all tools directly in headless mode including those requiring approval', async () => {
const agent = new GeneralChatAgent({
diff --git a/packages/agent-runtime/src/audit/__tests__/createSecurityBlacklistAudit.test.ts b/packages/agent-runtime/src/audit/__tests__/createSecurityBlacklistAudit.test.ts
new file mode 100644
index 00000000000..a733362611c
--- /dev/null
+++ b/packages/agent-runtime/src/audit/__tests__/createSecurityBlacklistAudit.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ createSecurityBlacklistAudit,
+ createSecurityBlacklistGlobalAudit,
+ SECURITY_BLACKLIST_AUDIT_TYPE,
+} from '../createSecurityBlacklistAudit';
+
+describe('createSecurityBlacklistAudit', () => {
+ describe('createSecurityBlacklistAudit', () => {
+ it('should return true for blacklisted commands using default blacklist', () => {
+ const audit = createSecurityBlacklistAudit();
+ // "rm -rf /" matches the default blacklist
+ expect(audit({ command: 'rm -rf /' })).toBe(true);
+ });
+
+ it('should return false for safe commands using default blacklist', () => {
+ const audit = createSecurityBlacklistAudit();
+ expect(audit({ command: 'ls -la' })).toBe(false);
+ });
+
+ it('should use blacklist from metadata when provided', () => {
+ const audit = createSecurityBlacklistAudit();
+ const customBlacklist = [
+ {
+ description: 'Block custom command',
+ match: { command: { pattern: 'custom-danger.*', type: 'regex' as const } },
+ },
+ ];
+
+ expect(
+ audit({ command: 'custom-danger --force' }, { securityBlacklist: customBlacklist }),
+ ).toBe(true);
+ // Default blacklist commands should not be blocked with custom blacklist
+ expect(audit({ command: 'rm -rf /' }, { securityBlacklist: customBlacklist })).toBe(false);
+ });
+
+ it('should fall back to DEFAULT_SECURITY_BLACKLIST when metadata has no blacklist', () => {
+ const audit = createSecurityBlacklistAudit();
+ // No securityBlacklist in metadata → uses default
+ expect(audit({ command: 'rm -rf /' }, {})).toBe(true);
+ expect(audit({ command: 'rm -rf /' }, { otherField: 'value' })).toBe(true);
+ });
+
+ it('should fall back to DEFAULT_SECURITY_BLACKLIST when metadata is undefined', () => {
+ const audit = createSecurityBlacklistAudit();
+ expect(audit({ command: 'rm -rf /' }, undefined)).toBe(true);
+ });
+
+ it('should return false for empty tool args', () => {
+ const audit = createSecurityBlacklistAudit();
+ expect(audit({})).toBe(false);
+ });
+
+ it('should detect sensitive file paths via default blacklist', () => {
+ const audit = createSecurityBlacklistAudit();
+ expect(audit({ path: '/home/user/.env' })).toBe(true);
+ expect(audit({ path: '/home/user/.ssh/id_rsa' })).toBe(true);
+ });
+
+ it('should return false when metadata provides empty blacklist', () => {
+ const audit = createSecurityBlacklistAudit();
+ expect(audit({ command: 'rm -rf /' }, { securityBlacklist: [] })).toBe(false);
+ });
+ });
+
+ describe('createSecurityBlacklistGlobalAudit', () => {
+ it('should return a valid GlobalInterventionAuditConfig', () => {
+ const config = createSecurityBlacklistGlobalAudit();
+
+ expect(config.type).toBe(SECURITY_BLACKLIST_AUDIT_TYPE);
+ expect(config.policy).toBe('always');
+ expect(typeof config.resolver).toBe('function');
+ });
+
+ it('should have a working resolver that blocks blacklisted commands', () => {
+ const config = createSecurityBlacklistGlobalAudit();
+
+ expect(config.resolver({ command: 'rm -rf /' })).toBe(true);
+ expect(config.resolver({ command: 'ls -la' })).toBe(false);
+ });
+ });
+
+ describe('SECURITY_BLACKLIST_AUDIT_TYPE', () => {
+ it('should be securityBlacklist', () => {
+ expect(SECURITY_BLACKLIST_AUDIT_TYPE).toBe('securityBlacklist');
+ });
+ });
+});
diff --git a/packages/agent-runtime/src/audit/createSecurityBlacklistAudit.ts b/packages/agent-runtime/src/audit/createSecurityBlacklistAudit.ts
new file mode 100644
index 00000000000..f94e95e4b90
--- /dev/null
+++ b/packages/agent-runtime/src/audit/createSecurityBlacklistAudit.ts
@@ -0,0 +1,31 @@
+import {
+ type DynamicInterventionResolver,
+ type GlobalInterventionAuditConfig,
+} from '@lobechat/types';
+
+import { InterventionChecker } from '../core/InterventionChecker';
+import { DEFAULT_SECURITY_BLACKLIST } from './defaultSecurityBlacklist';
+
+export const SECURITY_BLACKLIST_AUDIT_TYPE = 'securityBlacklist';
+
+/**
+ * Create a DynamicInterventionResolver that checks security blacklist rules.
+ * Reads blacklist from `metadata.securityBlacklist`, falls back to DEFAULT_SECURITY_BLACKLIST.
+ */
+export const createSecurityBlacklistAudit = (): DynamicInterventionResolver => {
+ return (toolArgs: Record<string, any>, metadata?: Record<string, any>): boolean => {
+ const securityBlacklist = metadata?.securityBlacklist ?? DEFAULT_SECURITY_BLACKLIST;
+ const result = InterventionChecker.checkSecurityBlacklist(securityBlacklist, toolArgs);
+ return result.blocked;
+ };
+};
+
+/**
+ * Create the default security blacklist global audit config.
+ * policy: 'always' ensures this cannot be bypassed by auto-run mode.
+ */
+export const createSecurityBlacklistGlobalAudit = (): GlobalInterventionAuditConfig => ({
+ policy: 'always',
+ resolver: createSecurityBlacklistAudit(),
+ type: SECURITY_BLACKLIST_AUDIT_TYPE,
+});
diff --git a/packages/agent-runtime/src/core/defaultSecurityBlacklist.ts b/packages/agent-runtime/src/audit/defaultSecurityBlacklist.ts
similarity index 68%
rename from packages/agent-runtime/src/core/defaultSecurityBlacklist.ts
rename to packages/agent-runtime/src/audit/defaultSecurityBlacklist.ts
index ff48f2067a0..e224a0fb032 100644
--- a/packages/agent-runtime/src/core/defaultSecurityBlacklist.ts
+++ b/packages/agent-runtime/src/audit/defaultSecurityBlacklist.ts
@@ -1,4 +1,4 @@
-import type { SecurityBlacklistConfig } from '@lobechat/types';
+import { type SecurityBlacklistConfig } from '@lobechat/types';
/**
* Default Security Blacklist
@@ -6,11 +6,14 @@ import type { SecurityBlacklistConfig } from '@lobechat/types';
* regardless of user settings (even in auto-run mode)
*
* This is the last line of defense against dangerous operations
+ *
+ * Note: `description` values are i18n keys (namespace: 'tool', prefix: 'securityBlacklist.')
+ * and are translated in the intervention UI via `t(description)`.
*/
export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
// ==================== File System Dangers ====================
{
- description: 'Recursive deletion of home directory is extremely dangerous',
+ description: 'securityBlacklist.rmHomeDir',
match: {
command: {
pattern: 'rm.*-r.*(~|\\$HOME|/Users/[^/]+|/home/[^/]+)/?\\s*$',
@@ -19,7 +22,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Recursive deletion of root directory will destroy the system',
+ description: 'securityBlacklist.rmRootDir',
match: {
command: {
pattern: 'rm.*-r.*/\\s*$',
@@ -28,7 +31,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Force recursive deletion without specific target is too dangerous',
+ description: 'securityBlacklist.rmForceRecursive',
match: {
command: {
pattern: 'rm\\s+-rf\\s+[~./]\\s*$',
@@ -39,7 +42,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
// ==================== System Configuration Dangers ====================
{
- description: 'Modifying /etc/passwd could lock you out of the system',
+ description: 'securityBlacklist.etcPasswd',
match: {
command: {
pattern: '.*(/etc/passwd|/etc/shadow).*',
@@ -48,7 +51,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Modifying sudoers file without proper validation is dangerous',
+ description: 'securityBlacklist.sudoers',
match: {
command: {
pattern: '.*/etc/sudoers.*',
@@ -59,7 +62,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
// ==================== Dangerous Commands ====================
{
- description: 'Fork bomb can crash the system',
+ description: 'securityBlacklist.forkBomb',
match: {
command: {
pattern: '.*:\\(\\).*\\{.*\\|.*&.*\\};.*:.*',
@@ -68,7 +71,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Writing random data to disk devices can destroy data',
+ description: 'securityBlacklist.ddDiskWrite',
match: {
command: {
pattern: 'dd.*of=/dev/(sd|hd|nvme).*',
@@ -77,7 +80,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Formatting system partitions will destroy data',
+ description: 'securityBlacklist.formatPartition',
match: {
command: {
pattern: '(mkfs|fdisk|parted).*(/dev/(sd|hd|nvme)|/)',
@@ -88,7 +91,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
// ==================== Network & Remote Access Dangers ====================
{
- description: 'Disabling firewall exposes system to attacks',
+ description: 'securityBlacklist.disableFirewall',
match: {
command: {
pattern: '(ufw\\s+disable|iptables\\s+-F|systemctl\\s+stop\\s+firewalld)',
@@ -97,7 +100,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Changing SSH configuration could lock you out',
+ description: 'securityBlacklist.sshConfig',
match: {
command: {
pattern: '.*(/etc/ssh/sshd_config).*',
@@ -108,7 +111,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
// ==================== Package Manager Dangers ====================
{
- description: 'Removing essential system packages can break the system',
+ description: 'securityBlacklist.removeSystemPackages',
match: {
command: {
pattern: '(apt|yum|dnf|pacman)\\s+(remove|purge|erase).*(systemd|kernel|glibc|bash|sudo)',
@@ -119,7 +122,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
// ==================== Kernel & System Core Dangers ====================
{
- description: 'Modifying kernel parameters without understanding can crash the system',
+ description: 'securityBlacklist.kernelParams',
match: {
command: {
pattern: 'echo.*>/proc/sys/.*',
@@ -128,7 +131,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Direct memory access is extremely dangerous',
+ description: 'securityBlacklist.directMemoryAccess',
match: {
command: {
pattern: '.*(/dev/(mem|kmem|port)).*',
@@ -139,7 +142,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
// ==================== Privilege Escalation Dangers ====================
{
- description: 'Changing file ownership of system directories is dangerous',
+ description: 'securityBlacklist.chownSystemDirs',
match: {
command: {
pattern: 'chown.*-R.*(/(etc|bin|sbin|usr|var|sys|proc)|~).*',
@@ -148,7 +151,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Setting SUID on shells or interpreters is a security risk',
+ description: 'securityBlacklist.suidShells',
match: {
command: {
pattern: 'chmod.*(4755|u\\+s).*(sh|bash|python|perl|ruby|node)',
@@ -159,7 +162,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
// ==================== Sensitive Information Leakage ====================
{
- description: 'Reading .env files may leak sensitive credentials and API keys',
+ description: 'securityBlacklist.envFiles',
match: {
command: {
pattern: '(cat|less|more|head|tail|vim|nano|vi|emacs|code).*\\.env.*',
@@ -168,7 +171,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Reading .env files may leak sensitive credentials and API keys',
+ description: 'securityBlacklist.envFiles',
match: {
path: {
pattern: '.*\\.env.*',
@@ -177,7 +180,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Reading SSH private keys can compromise system security',
+ description: 'securityBlacklist.sshPrivateKeys',
match: {
command: {
pattern:
@@ -187,7 +190,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Reading SSH private keys can compromise system security',
+ description: 'securityBlacklist.sshPrivateKeys',
match: {
path: {
pattern: '.*/\\.ssh/(id_rsa|id_ed25519|id_ecdsa)$',
@@ -196,7 +199,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Accessing AWS credentials can leak cloud access keys',
+ description: 'securityBlacklist.awsCredentials',
match: {
command: {
pattern: '(cat|less|more|head|tail|vim|nano|vi|emacs|code).*/\\.aws/credentials.*',
@@ -205,7 +208,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Accessing AWS credentials can leak cloud access keys',
+ description: 'securityBlacklist.awsCredentials',
match: {
path: {
pattern: '.*/\\.aws/credentials.*',
@@ -214,7 +217,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Reading Docker config may expose registry credentials',
+ description: 'securityBlacklist.dockerConfig',
match: {
command: {
pattern: '(cat|less|more|head|tail|vim|nano|vi|emacs|code).*/\\.docker/config\\.json.*',
@@ -223,7 +226,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Reading Docker config may expose registry credentials',
+ description: 'securityBlacklist.dockerConfig',
match: {
path: {
pattern: '.*/\\.docker/config\\.json$',
@@ -232,7 +235,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Reading Kubernetes config may expose cluster credentials',
+ description: 'securityBlacklist.kubeConfig',
match: {
command: {
pattern: '(cat|less|more|head|tail|vim|nano|vi|emacs|code).*/\\.kube/config.*',
@@ -241,7 +244,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Reading Kubernetes config may expose cluster credentials',
+ description: 'securityBlacklist.kubeConfig',
match: {
path: {
pattern: '.*/\\.kube/config$',
@@ -250,7 +253,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Reading Git credentials file may leak access tokens',
+ description: 'securityBlacklist.gitCredentials',
match: {
command: {
pattern: '(cat|less|more|head|tail|vim|nano|vi|emacs|code).*/\\.git-credentials.*',
@@ -259,7 +262,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Reading Git credentials file may leak access tokens',
+ description: 'securityBlacklist.gitCredentials',
match: {
path: {
pattern: '.*/\\.git-credentials$',
@@ -268,7 +271,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Reading npm token file may expose package registry credentials',
+ description: 'securityBlacklist.npmrc',
match: {
command: {
pattern: '(cat|less|more|head|tail|vim|nano|vi|emacs|code).*/\\.npmrc.*',
@@ -277,7 +280,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Reading npm token file may expose package registry credentials',
+ description: 'securityBlacklist.npmrc',
match: {
path: {
pattern: '.*/\\.npmrc$',
@@ -286,7 +289,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Reading history files may expose sensitive commands and credentials',
+ description: 'securityBlacklist.historyFiles',
match: {
command: {
pattern:
@@ -296,7 +299,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Reading history files may expose sensitive commands and credentials',
+ description: 'securityBlacklist.historyFiles',
match: {
path: {
pattern: '.*/\\.(bash_history|zsh_history|history)$',
@@ -305,7 +308,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Accessing browser credential storage may leak passwords',
+ description: 'securityBlacklist.browserCredentials',
match: {
command: {
pattern:
@@ -315,7 +318,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Reading GCP credentials may leak cloud service account keys',
+ description: 'securityBlacklist.gcpCredentials',
match: {
command: {
pattern: '(cat|less|more|head|tail|vim|nano|vi|emacs|code).*/\\.config/gcloud/.*\\.json.*',
@@ -324,7 +327,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [
},
},
{
- description: 'Reading GCP credentials may leak cloud service account keys',
+ description: 'securityBlacklist.gcpCredentials',
match: {
path: {
pattern: '.*/\\.config/gcloud/.*\\.json$',
diff --git a/packages/agent-runtime/src/audit/globalAudit.ts b/packages/agent-runtime/src/audit/globalAudit.ts
new file mode 100644
index 00000000000..decb0b2a49c
--- /dev/null
+++ b/packages/agent-runtime/src/audit/globalAudit.ts
@@ -0,0 +1,7 @@
+import { type GlobalInterventionAuditConfig } from '@lobechat/types';
+
+import { createSecurityBlacklistGlobalAudit } from './createSecurityBlacklistAudit';
+
+export const createDefaultGlobalAudits = (): GlobalInterventionAuditConfig[] => [
+ createSecurityBlacklistGlobalAudit(),
+];
diff --git a/packages/agent-runtime/src/audit/index.ts b/packages/agent-runtime/src/audit/index.ts
new file mode 100644
index 00000000000..58b795f1016
--- /dev/null
+++ b/packages/agent-runtime/src/audit/index.ts
@@ -0,0 +1,3 @@
+export * from './createSecurityBlacklistAudit';
+export * from './defaultSecurityBlacklist';
+export * from './globalAudit';
diff --git a/packages/agent-runtime/src/core/InterventionChecker.ts b/packages/agent-runtime/src/core/InterventionChecker.ts
index aa7dccf8acc..0f349ad4fd0 100644
--- a/packages/agent-runtime/src/core/InterventionChecker.ts
+++ b/packages/agent-runtime/src/core/InterventionChecker.ts
@@ -1,12 +1,12 @@
-import type {
- ArgumentMatcher,
- HumanInterventionPolicy,
- HumanInterventionRule,
- SecurityBlacklistRule,
- ShouldInterveneParams,
+import {
+ type ArgumentMatcher,
+ type HumanInterventionPolicy,
+ type HumanInterventionRule,
+ type SecurityBlacklistRule,
+ type ShouldInterveneParams,
} from '@lobechat/types';
-import { DEFAULT_SECURITY_BLACKLIST } from './defaultSecurityBlacklist';
+import { DEFAULT_SECURITY_BLACKLIST } from '../audit/defaultSecurityBlacklist';
/**
* Result of security blacklist check
diff --git a/packages/agent-runtime/src/core/__tests__/InterventionChecker.test.ts b/packages/agent-runtime/src/core/__tests__/InterventionChecker.test.ts
index ad390ee696c..d70db0cc0ec 100644
--- a/packages/agent-runtime/src/core/__tests__/InterventionChecker.test.ts
+++ b/packages/agent-runtime/src/core/__tests__/InterventionChecker.test.ts
@@ -1,7 +1,7 @@
-import type { HumanInterventionConfig, SecurityBlacklistConfig } from '@lobechat/types';
+import { type HumanInterventionConfig, type SecurityBlacklistConfig } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import { DEFAULT_SECURITY_BLACKLIST } from '../defaultSecurityBlacklist';
+import { DEFAULT_SECURITY_BLACKLIST } from '../../audit/defaultSecurityBlacklist';
import { InterventionChecker } from '../InterventionChecker';
describe('InterventionChecker', () => {
@@ -262,7 +262,7 @@ describe('InterventionChecker', () => {
command: 'rm -rf ~/',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe('Recursive deletion of home directory is extremely dangerous');
+ expect(result.reason).toBe('securityBlacklist.rmHomeDir');
});
it('should block rm -rf on macOS home directory', () => {
@@ -270,7 +270,7 @@ describe('InterventionChecker', () => {
command: 'rm -rf /Users/alice',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe('Recursive deletion of home directory is extremely dangerous');
+ expect(result.reason).toBe('securityBlacklist.rmHomeDir');
});
it('should block rm -rf on Linux home directory', () => {
@@ -278,7 +278,7 @@ describe('InterventionChecker', () => {
command: 'rm -rf /home/alice',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe('Recursive deletion of home directory is extremely dangerous');
+ expect(result.reason).toBe('securityBlacklist.rmHomeDir');
});
it('should block rm -rf with $HOME variable', () => {
@@ -286,7 +286,7 @@ describe('InterventionChecker', () => {
command: 'rm -rf $HOME',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe('Recursive deletion of home directory is extremely dangerous');
+ expect(result.reason).toBe('securityBlacklist.rmHomeDir');
});
it('should block rm -rf / command', () => {
@@ -294,7 +294,7 @@ describe('InterventionChecker', () => {
command: 'rm -rf /',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe('Recursive deletion of root directory will destroy the system');
+ expect(result.reason).toBe('securityBlacklist.rmRootDir');
});
it('should allow safe rm commands', () => {
@@ -309,7 +309,7 @@ describe('InterventionChecker', () => {
command: ':(){ :|:& };:',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe('Fork bomb can crash the system');
+ expect(result.reason).toBe('securityBlacklist.forkBomb');
});
it('should block dangerous dd commands to disk devices', () => {
@@ -317,7 +317,7 @@ describe('InterventionChecker', () => {
command: 'dd if=/dev/zero of=/dev/sda',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe('Writing random data to disk devices can destroy data');
+ expect(result.reason).toBe('securityBlacklist.ddDiskWrite');
});
it('should block reading .env files via command', () => {
@@ -325,9 +325,7 @@ describe('InterventionChecker', () => {
command: 'cat .env',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe(
- 'Reading .env files may leak sensitive credentials and API keys',
- );
+ expect(result.reason).toBe('securityBlacklist.envFiles');
});
it('should block reading .env files via path', () => {
@@ -335,9 +333,7 @@ describe('InterventionChecker', () => {
path: '/project/.env.local',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe(
- 'Reading .env files may leak sensitive credentials and API keys',
- );
+ expect(result.reason).toBe('securityBlacklist.envFiles');
});
it('should block reading SSH private keys via command', () => {
@@ -345,7 +341,7 @@ describe('InterventionChecker', () => {
command: 'cat ~/.ssh/id_rsa',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe('Reading SSH private keys can compromise system security');
+ expect(result.reason).toBe('securityBlacklist.sshPrivateKeys');
});
it('should block reading SSH private keys via path', () => {
@@ -353,7 +349,7 @@ describe('InterventionChecker', () => {
path: '/home/user/.ssh/id_ed25519',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe('Reading SSH private keys can compromise system security');
+ expect(result.reason).toBe('securityBlacklist.sshPrivateKeys');
});
it('should allow reading SSH public keys', () => {
@@ -368,7 +364,7 @@ describe('InterventionChecker', () => {
command: 'cat ~/.aws/credentials',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe('Accessing AWS credentials can leak cloud access keys');
+ expect(result.reason).toBe('securityBlacklist.awsCredentials');
});
it('should block reading AWS credentials via path', () => {
@@ -376,7 +372,7 @@ describe('InterventionChecker', () => {
path: '/home/user/.aws/credentials',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe('Accessing AWS credentials can leak cloud access keys');
+ expect(result.reason).toBe('securityBlacklist.awsCredentials');
});
it('should block reading Docker config', () => {
@@ -384,7 +380,7 @@ describe('InterventionChecker', () => {
command: 'less ~/.docker/config.json',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe('Reading Docker config may expose registry credentials');
+ expect(result.reason).toBe('securityBlacklist.dockerConfig');
});
it('should block reading Kubernetes config', () => {
@@ -392,7 +388,7 @@ describe('InterventionChecker', () => {
path: '/home/user/.kube/config',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe('Reading Kubernetes config may expose cluster credentials');
+ expect(result.reason).toBe('securityBlacklist.kubeConfig');
});
it('should block reading Git credentials', () => {
@@ -400,7 +396,7 @@ describe('InterventionChecker', () => {
command: 'cat ~/.git-credentials',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe('Reading Git credentials file may leak access tokens');
+ expect(result.reason).toBe('securityBlacklist.gitCredentials');
});
it('should block reading npm token file', () => {
@@ -408,9 +404,7 @@ describe('InterventionChecker', () => {
path: '/home/user/.npmrc',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe(
- 'Reading npm token file may expose package registry credentials',
- );
+ expect(result.reason).toBe('securityBlacklist.npmrc');
});
it('should block reading shell history files', () => {
@@ -418,9 +412,7 @@ describe('InterventionChecker', () => {
command: 'cat ~/.bash_history',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe(
- 'Reading history files may expose sensitive commands and credentials',
- );
+ expect(result.reason).toBe('securityBlacklist.historyFiles');
});
it('should block reading GCP credentials', () => {
@@ -428,7 +420,7 @@ describe('InterventionChecker', () => {
path: '/home/user/.config/gcloud/application_default_credentials.json',
});
expect(result.blocked).toBe(true);
- expect(result.reason).toBe('Reading GCP credentials may leak cloud service account keys');
+ expect(result.reason).toBe('securityBlacklist.gcpCredentials');
});
});
diff --git a/packages/agent-runtime/src/core/index.ts b/packages/agent-runtime/src/core/index.ts
index ae3c0329a5b..b5aac38a1ea 100644
--- a/packages/agent-runtime/src/core/index.ts
+++ b/packages/agent-runtime/src/core/index.ts
@@ -1,4 +1,3 @@
-export * from './defaultSecurityBlacklist';
export * from './InterventionChecker';
export * from './runtime';
export * from './UsageCounter';
diff --git a/packages/agent-runtime/src/index.ts b/packages/agent-runtime/src/index.ts
index a25f0c93279..5c13cc9b02b 100644
--- a/packages/agent-runtime/src/index.ts
+++ b/packages/agent-runtime/src/index.ts
@@ -1,4 +1,5 @@
export * from './agents';
+export * from './audit';
export * from './core';
export * from './groupOrchestration';
export * from './types';
diff --git a/packages/agent-runtime/src/types/generalAgent.ts b/packages/agent-runtime/src/types/generalAgent.ts
index cbf03190ec5..fbab265dbf4 100644
--- a/packages/agent-runtime/src/types/generalAgent.ts
+++ b/packages/agent-runtime/src/types/generalAgent.ts
@@ -1,4 +1,9 @@
-import type { ChatToolPayload, MessageToolCall } from '@lobechat/types';
+import {
+ type ChatToolPayload,
+ type DynamicInterventionResolver,
+ type GlobalInterventionAuditConfig,
+ type MessageToolCall,
+} from '@lobechat/types';
export interface GeneralAgentCallLLMInstructionPayload {
/** Force create a new assistant message (e.g., after compression) */
@@ -77,6 +82,17 @@ export interface GeneralAgentConfig {
/** Model's max context window token count (default: 128k) */
maxWindowToken?: number;
};
+ /**
+ * Dynamic intervention audits registry (per-tool)
+ * Used to evaluate runtime intervention policies for tools with dynamic config
+ */
+ dynamicInterventionAudits?: Record<string, DynamicInterventionResolver>;
+ /**
+ * Global intervention resolvers that run for EVERY tool call
+ * Evaluated in array order, before per-tool dynamic resolvers.
+ * When not provided, defaults to [createSecurityBlacklistGlobalAudit()]
+ */
+ globalInterventionAudits?: GlobalInterventionAuditConfig[];
modelRuntimeConfig?: {
/**
* Compression model configuration
diff --git a/packages/builtin-tool-local-system/src/__tests__/interventionAudit.test.ts b/packages/builtin-tool-local-system/src/__tests__/interventionAudit.test.ts
new file mode 100644
index 00000000000..afc178cb696
--- /dev/null
+++ b/packages/builtin-tool-local-system/src/__tests__/interventionAudit.test.ts
@@ -0,0 +1,148 @@
+import { describe, expect, it } from 'vitest';
+
+import { pathScopeAudit } from '../interventionAudit';
+
+describe('pathScopeAudit', () => {
+ const metadata = { workingDirectory: '/Users/me/project' };
+
+ describe('no intervention needed', () => {
+ it('should return false when no working directory in metadata', () => {
+ expect(pathScopeAudit({ path: '/anywhere' })).toBe(false);
+ expect(pathScopeAudit({ path: '/anywhere' }, {})).toBe(false);
+ });
+
+ it('should return false when path is within working directory', () => {
+ expect(pathScopeAudit({ path: '/Users/me/project/src/index.ts' }, metadata)).toBe(false);
+ });
+
+ it('should return false when relative path resolves within working directory', () => {
+ expect(pathScopeAudit({ path: 'src/index.ts' }, metadata)).toBe(false);
+ });
+
+ it('should return false when relative directory resolves within working directory', () => {
+ expect(pathScopeAudit({ directory: 'src' }, metadata)).toBe(false);
+ });
+
+ it('should resolve relative paths against tool scope when provided', () => {
+ expect(
+ pathScopeAudit(
+ { scope: 'packages', path: 'a.ts' },
+ { workingDirectory: '/Users/me/project' },
+ ),
+ ).toBe(false);
+ });
+
+ it('should return false when path equals working directory', () => {
+ expect(pathScopeAudit({ path: '/Users/me/project' }, metadata)).toBe(false);
+ });
+
+ it('should return false for empty tool args', () => {
+ expect(pathScopeAudit({}, metadata)).toBe(false);
+ });
+ });
+
+ describe('intervention required', () => {
+ it('should return true when path is outside working directory', () => {
+ expect(pathScopeAudit({ path: '/Users/me/other-project/file.ts' }, metadata)).toBe(true);
+ });
+
+ it('should return true when relative path traversal escapes working directory', () => {
+ expect(pathScopeAudit({ path: '../other-project/file.ts' }, metadata)).toBe(true);
+ });
+
+ it('should return true when file_path is outside working directory', () => {
+ expect(pathScopeAudit({ file_path: '/tmp/secret.txt' }, metadata)).toBe(true);
+ });
+
+ it('should return true when directory is outside working directory', () => {
+ expect(pathScopeAudit({ directory: '/etc' }, metadata)).toBe(true);
+ });
+
+ it('should return true when scope is outside working directory', () => {
+ expect(pathScopeAudit({ scope: '/Users/me/other-project' }, metadata)).toBe(true);
+ });
+
+ it('should return true when pattern is an absolute glob outside working directory', () => {
+ expect(pathScopeAudit({ pattern: '/Users/me/other/**/*.ts' }, metadata)).toBe(true);
+ });
+
+ it('should return false when pattern is within working directory', () => {
+ expect(pathScopeAudit({ pattern: '/Users/me/project/src/**/*.ts' }, metadata)).toBe(false);
+ });
+
+ it('should ignore relative glob patterns (not a path)', () => {
+ expect(pathScopeAudit({ pattern: '**/*.ts' }, metadata)).toBe(false);
+ expect(pathScopeAudit({ pattern: 'src/**/*.tsx' }, metadata)).toBe(false);
+ });
+
+ it('should ignore regex patterns from grepContent', () => {
+ expect(pathScopeAudit({ pattern: 'TODO|FIXME' }, metadata)).toBe(false);
+ expect(pathScopeAudit({ pattern: 'function\\s+\\w+' }, metadata)).toBe(false);
+ expect(pathScopeAudit({ pattern: '^import .* from' }, metadata)).toBe(false);
+ });
+
+ it('should return true when any path in items is outside working directory', () => {
+ expect(
+ pathScopeAudit(
+ {
+ items: [{ oldPath: '/Users/me/project/a.ts', newPath: '/Users/me/other/b.ts' }],
+ },
+ metadata,
+ ),
+ ).toBe(true);
+ });
+ });
+
+ describe('items array handling', () => {
+ it('should return false when all items paths are within working directory', () => {
+ expect(
+ pathScopeAudit(
+ {
+ items: [
+ { oldPath: '/Users/me/project/a.ts', newPath: '/Users/me/project/b.ts' },
+ { oldPath: '/Users/me/project/c.ts', newPath: '/Users/me/project/d.ts' },
+ ],
+ },
+ metadata,
+ ),
+ ).toBe(false);
+ });
+
+ it('should handle items with only oldPath', () => {
+ expect(pathScopeAudit({ items: [{ oldPath: '/outside/path.ts' }] }, metadata)).toBe(true);
+ });
+
+ it('should handle items with only newPath', () => {
+ expect(pathScopeAudit({ items: [{ newPath: '/outside/path.ts' }] }, metadata)).toBe(true);
+ });
+ });
+
+ describe('mixed parameters', () => {
+ it('should return true if any parameter is outside, even if others are inside', () => {
+ expect(
+ pathScopeAudit({ path: '/Users/me/project/file.ts', scope: '/Users/me/other' }, metadata),
+ ).toBe(true);
+ });
+
+ it('should return false when all parameters are within working directory', () => {
+ expect(
+ pathScopeAudit(
+ { path: '/Users/me/project/src/file.ts', scope: '/Users/me/project' },
+ metadata,
+ ),
+ ).toBe(false);
+ });
+ });
+
+ describe('path traversal prevention', () => {
+ it('should catch path traversal that escapes working directory', () => {
+ expect(pathScopeAudit({ path: '/Users/me/project/../other/file.ts' }, metadata)).toBe(true);
+ });
+
+ it('should allow path traversal that stays within working directory', () => {
+ expect(pathScopeAudit({ path: '/Users/me/project/src/../lib/file.ts' }, metadata)).toBe(
+ false,
+ );
+ });
+ });
+});
diff --git a/packages/builtin-tool-local-system/src/client/Intervention/EditLocalFile/index.tsx b/packages/builtin-tool-local-system/src/client/Intervention/EditLocalFile/index.tsx
index 0cbefcbc038..79e918f2064 100644
--- a/packages/builtin-tool-local-system/src/client/Intervention/EditLocalFile/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Intervention/EditLocalFile/index.tsx
@@ -3,13 +3,15 @@ import type { BuiltinInterventionProps } from '@lobechat/types';
import { CodeDiff, Flexbox, Icon, Skeleton, Text } from '@lobehub/ui';
import { ChevronRight } from 'lucide-react';
import path from 'path-browserify-esm';
-import React, { memo, useMemo } from 'react';
+import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import useSWR from 'swr';
import { LocalFile, LocalFolder } from '@/features/LocalFile';
import { localFileService } from '@/services/electron/localFileService';
+import OutOfScopeWarning from '../OutOfScopeWarning';
+
const EditLocalFile = memo<BuiltinInterventionProps<EditLocalFileParams>>(({ args }) => {
const { t } = useTranslation('tool');
const { base, dir } = path.parse(args.file_path);
@@ -38,6 +40,7 @@ const EditLocalFile = memo<BuiltinInterventionProps<EditLocalFileParams>>(({ arg
return (
<Flexbox gap={12}>
+ <OutOfScopeWarning paths={[args.file_path]} />
<Flexbox horizontal>
<LocalFolder path={dir} />
<Icon icon={ChevronRight} />
diff --git a/packages/builtin-tool-local-system/src/client/Intervention/GlobLocalFiles/index.tsx b/packages/builtin-tool-local-system/src/client/Intervention/GlobLocalFiles/index.tsx
new file mode 100644
index 00000000000..138a8e45590
--- /dev/null
+++ b/packages/builtin-tool-local-system/src/client/Intervention/GlobLocalFiles/index.tsx
@@ -0,0 +1,28 @@
+import { type GlobFilesParams } from '@lobechat/electron-client-ipc';
+import { type BuiltinInterventionProps } from '@lobechat/types';
+import { Flexbox, Highlighter, Text } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import OutOfScopeWarning from '../OutOfScopeWarning';
+
+const GlobLocalFiles = memo<BuiltinInterventionProps<GlobFilesParams>>(({ args }) => {
+ const { t } = useTranslation('tool');
+ const { pattern } = args;
+
+ return (
+ <Flexbox gap={12}>
+ <OutOfScopeWarning paths={[pattern]} />
+ <Flexbox gap={4}>
+ <Text type="secondary">{t('localFiles.globFiles.pattern')}</Text>
+ <Highlighter language="text" showLanguage={false} variant="outlined">
+ {pattern}
+ </Highlighter>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+GlobLocalFiles.displayName = 'GlobLocalFilesIntervention';
+
+export default GlobLocalFiles;
diff --git a/packages/builtin-tool-local-system/src/client/Intervention/GrepContent/index.tsx b/packages/builtin-tool-local-system/src/client/Intervention/GrepContent/index.tsx
new file mode 100644
index 00000000000..3500b5316c2
--- /dev/null
+++ b/packages/builtin-tool-local-system/src/client/Intervention/GrepContent/index.tsx
@@ -0,0 +1,41 @@
+import { type GrepContentParams } from '@lobechat/electron-client-ipc';
+import { type BuiltinInterventionProps } from '@lobechat/types';
+import { Flexbox, Highlighter, Text } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { LocalFolder } from '@/features/LocalFile';
+
+import OutOfScopeWarning from '../OutOfScopeWarning';
+
+const GrepContent = memo<BuiltinInterventionProps<GrepContentParams>>(({ args }) => {
+ const { t } = useTranslation('tool');
+ const { pattern, scope, glob, type } = args;
+
+ return (
+ <Flexbox gap={12}>
+ <OutOfScopeWarning paths={scope ? [scope] : []} />
+ {scope && <LocalFolder path={scope} />}
+ <Flexbox gap={4}>
+ <Text type="secondary">{t('localFiles.grepContent.pattern')}</Text>
+ <Highlighter language="regex" showLanguage={false} variant="outlined">
+ {pattern}
+ </Highlighter>
+ </Flexbox>
+ {glob && (
+ <Text style={{ fontSize: 12 }} type="secondary">
+ {t('localFiles.grepContent.glob')}: {glob}
+ </Text>
+ )}
+ {type && (
+ <Text style={{ fontSize: 12 }} type="secondary">
+ {t('localFiles.grepContent.type')}: {type}
+ </Text>
+ )}
+ </Flexbox>
+ );
+});
+
+GrepContent.displayName = 'GrepContentIntervention';
+
+export default GrepContent;
diff --git a/packages/builtin-tool-local-system/src/client/Intervention/ListLocalFiles/index.tsx b/packages/builtin-tool-local-system/src/client/Intervention/ListLocalFiles/index.tsx
new file mode 100644
index 00000000000..57512bb071e
--- /dev/null
+++ b/packages/builtin-tool-local-system/src/client/Intervention/ListLocalFiles/index.tsx
@@ -0,0 +1,23 @@
+import type { ListLocalFileParams } from '@lobechat/electron-client-ipc';
+import type { BuiltinInterventionProps } from '@lobechat/types';
+import { Flexbox } from '@lobehub/ui';
+import { memo } from 'react';
+
+import { LocalFolder } from '@/features/LocalFile';
+
+import OutOfScopeWarning from '../OutOfScopeWarning';
+
+const ListLocalFiles = memo<BuiltinInterventionProps<ListLocalFileParams>>(({ args }) => {
+ const { path } = args;
+
+ return (
+ <Flexbox gap={12}>
+ <OutOfScopeWarning paths={[path]} />
+ <LocalFolder path={path} />
+ </Flexbox>
+ );
+});
+
+ListLocalFiles.displayName = 'ListLocalFilesIntervention';
+
+export default ListLocalFiles;
diff --git a/packages/builtin-tool-local-system/src/client/Intervention/MoveLocalFiles/index.tsx b/packages/builtin-tool-local-system/src/client/Intervention/MoveLocalFiles/index.tsx
index 01190723e02..56e13a2abb5 100644
--- a/packages/builtin-tool-local-system/src/client/Intervention/MoveLocalFiles/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Intervention/MoveLocalFiles/index.tsx
@@ -1,17 +1,22 @@
import type { MoveLocalFilesParams } from '@lobechat/electron-client-ipc';
import type { BuiltinInterventionProps } from '@lobechat/types';
import { Flexbox, Text } from '@lobehub/ui';
-import { memo } from 'react';
+import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import OutOfScopeWarning from '../OutOfScopeWarning';
import MoveFileItem from './MoveFileItem';
const MoveLocalFiles = memo<BuiltinInterventionProps<MoveLocalFilesParams>>(({ args }) => {
const { items } = args;
const { t } = useTranslation('tool');
+ // Collect all paths (source and destination) for validation
+ const allPaths = useMemo(() => items.flatMap((item) => [item.oldPath, item.newPath]), [items]);
+
return (
<Flexbox gap={8}>
+ <OutOfScopeWarning paths={allPaths} />
<Text type="secondary">{t('localFiles.moveFiles.itemsToMove', { count: items.length })}</Text>
<Flexbox gap={6}>
{items.map((item, index) => (
diff --git a/packages/builtin-tool-local-system/src/client/Intervention/OutOfScopeWarning.tsx b/packages/builtin-tool-local-system/src/client/Intervention/OutOfScopeWarning.tsx
new file mode 100644
index 00000000000..c2cc565677e
--- /dev/null
+++ b/packages/builtin-tool-local-system/src/client/Intervention/OutOfScopeWarning.tsx
@@ -0,0 +1,83 @@
+import { Alert, Flexbox } from '@lobehub/ui';
+import path from 'path-browserify-esm';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+
+interface OutOfScopeWarningProps {
+ /**
+ * The path(s) to check
+ */
+ paths: string[];
+}
+
+/**
+ * Check if a path is within the working directory
+ */
+const isPathWithinWorkingDirectory = (targetPath: string, workingDirectory: string): boolean => {
+ const normalizedTarget = path.resolve(targetPath);
+ const normalizedWorkingDir = path.resolve(workingDirectory);
+
+ return (
+ normalizedTarget === normalizedWorkingDir ||
+ normalizedTarget.startsWith(normalizedWorkingDir + path.sep)
+ );
+};
+
+/**
+ * Warning component displayed in Intervention UI when paths are outside the working directory
+ */
+const OutOfScopeWarning = memo<OutOfScopeWarningProps>(({ paths }) => {
+ const { t } = useTranslation('tool');
+
+ // Get working directory from topic or agent store
+ const topicWorkingDir = useChatStore(topicSelectors.currentTopicWorkingDirectory);
+ const agentWorkingDir = useAgentStore(agentSelectors.currentAgentWorkingDirectory);
+ const workingDirectory = topicWorkingDir || agentWorkingDir;
+
+ // Find paths that are outside the working directory
+ const outsidePaths = useMemo(() => {
+ if (!workingDirectory) return [];
+ return paths.filter((p) => p && !isPathWithinWorkingDirectory(p, workingDirectory));
+ }, [paths, workingDirectory]);
+
+ // Don't render if no working directory set or all paths are within scope
+ if (!workingDirectory || outsidePaths.length === 0) {
+ return null;
+ }
+
+ return (
+ <Alert
+ showIcon
+ title={t('localFiles.outOfScope.warning')}
+ type="warning"
+ variant="borderless"
+ description={
+ <Flexbox gap={4} style={{ fontSize: 12 }}>
+ <div>
+ <strong>{t('localFiles.outOfScope.workingDirectory')}:</strong>{' '}
+ <code>{workingDirectory}</code>
+ </div>
+ <div>
+ <strong>{t('localFiles.outOfScope.requestedPaths')}:</strong>
+ </div>
+ <ul style={{ margin: 0, paddingLeft: 20 }}>
+ {outsidePaths.map((p, i) => (
+ <li key={i}>
+ <code>{p}</code>
+ </li>
+ ))}
+ </ul>
+ </Flexbox>
+ }
+ />
+ );
+});
+
+OutOfScopeWarning.displayName = 'OutOfScopeWarning';
+
+export default OutOfScopeWarning;
diff --git a/packages/builtin-tool-local-system/src/client/Intervention/ReadLocalFile/index.tsx b/packages/builtin-tool-local-system/src/client/Intervention/ReadLocalFile/index.tsx
new file mode 100644
index 00000000000..5d97b79b1ba
--- /dev/null
+++ b/packages/builtin-tool-local-system/src/client/Intervention/ReadLocalFile/index.tsx
@@ -0,0 +1,36 @@
+import type { LocalReadFileParams } from '@lobechat/electron-client-ipc';
+import type { BuiltinInterventionProps } from '@lobechat/types';
+import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { ChevronRight } from 'lucide-react';
+import path from 'path-browserify-esm';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { LocalFile, LocalFolder } from '@/features/LocalFile';
+
+import OutOfScopeWarning from '../OutOfScopeWarning';
+
+const ReadLocalFile = memo<BuiltinInterventionProps<LocalReadFileParams>>(({ args }) => {
+ const { t } = useTranslation('tool');
+ const { base, dir } = path.parse(args.path || '');
+
+ return (
+ <Flexbox gap={12}>
+ <OutOfScopeWarning paths={[args.path]} />
+ <Flexbox horizontal>
+ <LocalFolder path={dir} />
+ <Icon icon={ChevronRight} />
+ <LocalFile name={base} path={args.path} />
+ </Flexbox>
+ {args.loc && (
+ <Text style={{ fontSize: 12 }} type="secondary">
+ {t('localFiles.readFile.lineRange', { end: args.loc[1], start: args.loc[0] })}
+ </Text>
+ )}
+ </Flexbox>
+ );
+});
+
+ReadLocalFile.displayName = 'ReadLocalFileIntervention';
+
+export default ReadLocalFile;
diff --git a/packages/builtin-tool-local-system/src/client/Intervention/RenameLocalFile/index.tsx b/packages/builtin-tool-local-system/src/client/Intervention/RenameLocalFile/index.tsx
new file mode 100644
index 00000000000..ab79ce631af
--- /dev/null
+++ b/packages/builtin-tool-local-system/src/client/Intervention/RenameLocalFile/index.tsx
@@ -0,0 +1,35 @@
+import type { RenameLocalFileParams } from '@lobechat/electron-client-ipc';
+import type { BuiltinInterventionProps } from '@lobechat/types';
+import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { ArrowRight, ChevronRight } from 'lucide-react';
+import path from 'path-browserify-esm';
+import { memo } from 'react';
+
+import { LocalFile, LocalFolder } from '@/features/LocalFile';
+
+import OutOfScopeWarning from '../OutOfScopeWarning';
+
+const RenameLocalFile = memo<BuiltinInterventionProps<RenameLocalFileParams>>(({ args }) => {
+ const { path: filePath, newName } = args;
+ const { base, dir } = path.parse(filePath || '');
+
+ return (
+ <Flexbox gap={12}>
+ <OutOfScopeWarning paths={[filePath]} />
+ <Flexbox horizontal>
+ <LocalFolder path={dir} />
+ <Icon icon={ChevronRight} />
+ <LocalFile name={base} path={filePath} />
+ </Flexbox>
+ <Flexbox align="center" gap={8} horizontal>
+ <Text type="secondary">{base}</Text>
+ <Icon icon={ArrowRight} />
+ <Text>{newName}</Text>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+RenameLocalFile.displayName = 'RenameLocalFileIntervention';
+
+export default RenameLocalFile;
diff --git a/packages/builtin-tool-local-system/src/client/Intervention/SearchLocalFiles/index.tsx b/packages/builtin-tool-local-system/src/client/Intervention/SearchLocalFiles/index.tsx
new file mode 100644
index 00000000000..1f6d3f4bbe9
--- /dev/null
+++ b/packages/builtin-tool-local-system/src/client/Intervention/SearchLocalFiles/index.tsx
@@ -0,0 +1,28 @@
+import { type LocalSearchFilesParams } from '@lobechat/electron-client-ipc';
+import { type BuiltinInterventionProps } from '@lobechat/types';
+import { Flexbox, Text } from '@lobehub/ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { LocalFolder } from '@/features/LocalFile';
+
+import OutOfScopeWarning from '../OutOfScopeWarning';
+
+const SearchLocalFiles = memo<BuiltinInterventionProps<LocalSearchFilesParams>>(({ args }) => {
+ const { t } = useTranslation('tool');
+ const { keywords, scope } = args;
+
+ return (
+ <Flexbox gap={12}>
+ <OutOfScopeWarning paths={scope ? [scope] : []} />
+ {scope && <LocalFolder path={scope} />}
+ <Text type="secondary">
+ {t('localFiles.searchFiles.keywords')}: {keywords}
+ </Text>
+ </Flexbox>
+ );
+});
+
+SearchLocalFiles.displayName = 'SearchLocalFilesIntervention';
+
+export default SearchLocalFiles;
diff --git a/packages/builtin-tool-local-system/src/client/Intervention/WriteFile/index.tsx b/packages/builtin-tool-local-system/src/client/Intervention/WriteFile/index.tsx
index 7f0734e9259..1a14e677bf8 100644
--- a/packages/builtin-tool-local-system/src/client/Intervention/WriteFile/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Intervention/WriteFile/index.tsx
@@ -3,11 +3,13 @@ import type { BuiltinInterventionProps } from '@lobechat/types';
import { Flexbox, Highlighter, Icon, Text } from '@lobehub/ui';
import { ChevronRight } from 'lucide-react';
import path from 'path-browserify-esm';
-import React, { memo, useMemo } from 'react';
+import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { LocalFile, LocalFolder } from '@/features/LocalFile';
+import OutOfScopeWarning from '../OutOfScopeWarning';
+
const WriteFile = memo<BuiltinInterventionProps<WriteLocalFileParams>>(({ args }) => {
const { t } = useTranslation('tool');
const { base, dir, ext } = path.parse(args.path || '');
@@ -37,6 +39,7 @@ const WriteFile = memo<BuiltinInterventionProps<WriteLocalFileParams>>(({ args }
return (
<Flexbox gap={12}>
+ <OutOfScopeWarning paths={[args.path]} />
<Flexbox horizontal>
<LocalFolder path={dir} />
<Icon icon={ChevronRight} />
diff --git a/packages/builtin-tool-local-system/src/client/Intervention/index.ts b/packages/builtin-tool-local-system/src/client/Intervention/index.ts
index 3896b5da9e0..92a2e3fcb4d 100644
--- a/packages/builtin-tool-local-system/src/client/Intervention/index.ts
+++ b/packages/builtin-tool-local-system/src/client/Intervention/index.ts
@@ -1,7 +1,13 @@
import { LocalSystemApiName } from '../..';
import EditLocalFile from './EditLocalFile';
+import GlobLocalFiles from './GlobLocalFiles';
+import GrepContent from './GrepContent';
+import ListLocalFiles from './ListLocalFiles';
import MoveLocalFiles from './MoveLocalFiles';
+import ReadLocalFile from './ReadLocalFile';
+import RenameLocalFile from './RenameLocalFile';
import RunCommand from './RunCommand';
+import SearchLocalFiles from './SearchLocalFiles';
import WriteFile from './WriteFile';
/**
@@ -9,7 +15,13 @@ import WriteFile from './WriteFile';
*/
export const LocalSystemInterventions = {
[LocalSystemApiName.editLocalFile]: EditLocalFile,
+ [LocalSystemApiName.globLocalFiles]: GlobLocalFiles,
+ [LocalSystemApiName.grepContent]: GrepContent,
+ [LocalSystemApiName.listLocalFiles]: ListLocalFiles,
[LocalSystemApiName.moveLocalFiles]: MoveLocalFiles,
+ [LocalSystemApiName.readLocalFile]: ReadLocalFile,
+ [LocalSystemApiName.renameLocalFile]: RenameLocalFile,
[LocalSystemApiName.runCommand]: RunCommand,
+ [LocalSystemApiName.searchLocalFiles]: SearchLocalFiles,
[LocalSystemApiName.writeLocalFile]: WriteFile,
};
diff --git a/packages/builtin-tool-local-system/src/executor/index.ts b/packages/builtin-tool-local-system/src/executor/index.ts
index 210428d824e..229cf9dc17c 100644
--- a/packages/builtin-tool-local-system/src/executor/index.ts
+++ b/packages/builtin-tool-local-system/src/executor/index.ts
@@ -1,3 +1,4 @@
+/* eslint-disable import-x/consistent-type-specifier-style */
import type {
EditLocalFileParams,
EditLocalFileResult,
@@ -38,7 +39,7 @@ import {
formatRenameResult,
formatWriteResult,
} from '@lobechat/prompts';
-import type { BuiltinToolResult } from '@lobechat/types';
+import { type BuiltinToolResult } from '@lobechat/types';
import { BaseExecutor } from '@lobechat/types';
import { localFileService } from '@/services/electron/localFileService';
@@ -58,6 +59,7 @@ import type {
RunCommandState,
} from '../types';
import { LocalSystemIdentifier } from '../types';
+import { resolveArgsWithScope } from '../utils/path';
const LocalSystemApiEnum = {
editLocalFile: 'editLocalFile' as const,
@@ -167,11 +169,17 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {
searchLocalFiles = async (params: LocalSearchFilesParams): Promise<BuiltinToolResult> => {
try {
- const result: LocalFileItem[] = await localFileService.searchLocalFiles(params);
+ const resolvedParams = resolveArgsWithScope(params, 'directory');
+
+ const result: LocalFileItem[] = await localFileService.searchLocalFiles(resolvedParams);
// Extract engine from first result (all results use same engine)
const engine = result[0]?.engine;
- const state: LocalFileSearchState = { engine, searchResults: result };
+ const state: LocalFileSearchState = {
+ engine,
+ resolvedPath: resolvedParams.directory,
+ searchResults: result,
+ };
const content = formatFileSearchResults(result);
@@ -424,7 +432,9 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {
grepContent = async (params: GrepContentParams): Promise<BuiltinToolResult> => {
try {
- const result: GrepContentResult = await localFileService.grepContent(params);
+ const resolvedParams = resolveArgsWithScope(params, 'path');
+
+ const result: GrepContentResult = await localFileService.grepContent(resolvedParams);
const content = result.success
? formatGrepResults({
@@ -433,7 +443,11 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {
})
: `Search failed: ${result.error || 'Unknown error'}`;
- const state: GrepContentState = { message: content.split('\n')[0], result };
+ const state: GrepContentState = {
+ message: content.split('\n')[0],
+ resolvedPath: resolvedParams.path,
+ result,
+ };
return {
content,
@@ -451,7 +465,9 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {
globLocalFiles = async (params: GlobFilesParams): Promise<BuiltinToolResult> => {
try {
- const result: GlobFilesResult = await localFileService.globFiles(params);
+ const resolvedParams = resolveArgsWithScope(params, 'pattern');
+
+ const result: GlobFilesResult = await localFileService.globFiles(resolvedParams);
const content = result.success
? formatGlobResults({
@@ -460,7 +476,11 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {
})
: `Glob search failed: ${result.error || 'Unknown error'}`;
- const state: GlobFilesState = { message: content.split('\n')[0], result };
+ const state: GlobFilesState = {
+ message: content.split('\n')[0],
+ resolvedPath: resolvedParams.pattern,
+ result,
+ };
return {
content,
diff --git a/packages/builtin-tool-local-system/src/index.ts b/packages/builtin-tool-local-system/src/index.ts
index 3e0f9955959..fe954161488 100644
--- a/packages/builtin-tool-local-system/src/index.ts
+++ b/packages/builtin-tool-local-system/src/index.ts
@@ -1,3 +1,4 @@
+export { pathScopeAudit } from './interventionAudit';
export { LocalSystemManifest } from './manifest';
export { systemPrompt } from './systemRole';
export {
diff --git a/packages/builtin-tool-local-system/src/interventionAudit.ts b/packages/builtin-tool-local-system/src/interventionAudit.ts
new file mode 100644
index 00000000000..1119b3d5c4e
--- /dev/null
+++ b/packages/builtin-tool-local-system/src/interventionAudit.ts
@@ -0,0 +1,88 @@
+import { type DynamicInterventionResolver } from '@lobechat/types';
+
+import { normalizePathForScope, resolvePathWithScope } from './utils/path';
+
+/**
+ * Check if a path is within the working directory
+ */
+const isPathWithinWorkingDirectory = (
+ targetPath: string,
+ workingDirectory: string,
+ resolveAgainstScope: string,
+): boolean => {
+ const resolvedTarget = resolvePathWithScope(targetPath, resolveAgainstScope) ?? targetPath;
+ const normalizedTarget = normalizePathForScope(resolvedTarget);
+ const normalizedWorkingDir = normalizePathForScope(workingDirectory);
+
+ return (
+ normalizedTarget === normalizedWorkingDir ||
+ normalizedTarget.startsWith(normalizedWorkingDir + '/')
+ );
+};
+
+/**
+ * Extract all path values from tool arguments
+ * Looks for common path parameter names used in local-system tools
+ */
+const extractPaths = (toolArgs: Record<string, any>): string[] => {
+ const paths: string[] = [];
+ const pathParamNames = ['path', 'file_path', 'directory', 'oldPath', 'newPath'];
+
+ for (const paramName of pathParamNames) {
+ const pathValue = toolArgs[paramName];
+ if (pathValue && typeof pathValue === 'string') {
+ paths.push(pathValue);
+ }
+ }
+
+ // Only check 'pattern' when it's an absolute path (e.g. glob like /Users/me/**/*.ts).
+ // Relative globs (e.g. **/*.ts) and regex patterns (e.g. TODO|FIXME) are not paths.
+ if (typeof toolArgs.pattern === 'string' && toolArgs.pattern.startsWith('/')) {
+ paths.push(toolArgs.pattern);
+ }
+
+ // Handle 'items' array for moveLocalFiles (contains oldPath/newPath objects)
+ if (Array.isArray(toolArgs.items)) {
+ for (const item of toolArgs.items) {
+ if (typeof item === 'object') {
+ if (item.oldPath) paths.push(item.oldPath);
+ if (item.newPath) paths.push(item.newPath);
+ }
+ }
+ }
+
+ return paths;
+};
+
+/**
+ * Path scope audit for local-system tools
+ * Returns true if any path is outside the working directory (requires intervention)
+ */
+export const pathScopeAudit: DynamicInterventionResolver = (
+ toolArgs: Record<string, any>,
+ metadata?: Record<string, any>,
+): boolean => {
+ const workingDirectory = metadata?.workingDirectory as string | undefined;
+ const toolScope = toolArgs.scope as string | undefined;
+
+ // If no working directory is set, no intervention needed
+ if (!workingDirectory) {
+ return false;
+ }
+
+ // Match runtime behavior: a tool-provided scope is interpreted relative to workingDirectory.
+ // If the resolved scope escapes the workingDirectory, intervention is required.
+ if (toolScope && !isPathWithinWorkingDirectory(toolScope, workingDirectory, workingDirectory)) {
+ return true;
+ }
+
+ const effectiveScope =
+ resolvePathWithScope(toolScope, workingDirectory) ?? toolScope ?? workingDirectory;
+
+ const paths = extractPaths(toolArgs);
+
+ // Return true if any path is outside the working directory
+ return paths.some(
+ (path) => !isPathWithinWorkingDirectory(path, workingDirectory, effectiveScope),
+ );
+};
diff --git a/packages/builtin-tool-local-system/src/manifest.ts b/packages/builtin-tool-local-system/src/manifest.ts
index 6ec57f0085a..b0c02cf3043 100644
--- a/packages/builtin-tool-local-system/src/manifest.ts
+++ b/packages/builtin-tool-local-system/src/manifest.ts
@@ -1,4 +1,4 @@
-import type { BuiltinToolManifest } from '@lobechat/types';
+import { type BuiltinToolManifest } from '@lobechat/types';
import { systemPrompt } from './systemRole';
import { LocalSystemApiName, LocalSystemIdentifier } from './types';
@@ -7,7 +7,14 @@ export const LocalSystemManifest: BuiltinToolManifest = {
api: [
{
description:
- 'List files and folders in a specified directory. Returns file/folder names with metadata (size, modified time). Results are sorted by modified time (newest first) by default and limited to 100 items.',
+ 'List files and folders in a specified directory. Input should be a path. Output is a JSON array of file/folder names.',
+ humanIntervention: {
+ dynamic: {
+ default: 'never',
+ policy: 'required',
+ type: 'pathScopeAudit',
+ },
+ },
name: LocalSystemApiName.listLocalFiles,
parameters: {
properties: {
@@ -40,6 +47,13 @@ export const LocalSystemManifest: BuiltinToolManifest = {
{
description:
'Read the content of a specific file. Input should be the file path. Output is the file content as a string.',
+ humanIntervention: {
+ dynamic: {
+ default: 'never',
+ policy: 'required',
+ type: 'pathScopeAudit',
+ },
+ },
name: LocalSystemApiName.readLocalFile,
parameters: {
properties: {
@@ -63,6 +77,13 @@ export const LocalSystemManifest: BuiltinToolManifest = {
{
description:
'Search for files within the workspace based on a query string and optional filter options. Input should include the search query and any filter options. Output is a JSON array of matching file paths.',
+ humanIntervention: {
+ dynamic: {
+ default: 'never',
+ policy: 'required',
+ type: 'pathScopeAudit',
+ },
+ },
name: LocalSystemApiName.searchLocalFiles,
parameters: {
properties: {
@@ -81,10 +102,6 @@ export const LocalSystemManifest: BuiltinToolManifest = {
format: 'date-time',
type: 'string',
},
- directory: {
- description: 'Limit the search to this specific directory path',
- type: 'string',
- },
exclude: {
description: 'Array of file or directory paths to exclude',
items: {
@@ -103,6 +120,11 @@ export const LocalSystemManifest: BuiltinToolManifest = {
description: 'The search keywords string (can include partial names or keywords)',
type: 'string',
},
+ scope: {
+ description:
+ 'Working directory scope. Limits the search to this directory. Defaults to the current working directory.',
+ type: 'string',
+ },
limit: {
description: 'Limit the number of results returned',
type: 'number',
@@ -139,7 +161,13 @@ 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',
+ humanIntervention: {
+ dynamic: {
+ default: 'never',
+ policy: 'required',
+ type: 'pathScopeAudit',
+ },
+ },
name: LocalSystemApiName.moveLocalFiles,
parameters: {
properties: {
@@ -170,6 +198,13 @@ export const LocalSystemManifest: BuiltinToolManifest = {
{
description:
'Rename a file or folder in its current location. Input should be the current full path and the new name.',
+ humanIntervention: {
+ dynamic: {
+ default: 'never',
+ policy: 'required',
+ type: 'pathScopeAudit',
+ },
+ },
name: LocalSystemApiName.renameLocalFile,
parameters: {
properties: {
@@ -189,7 +224,13 @@ export const LocalSystemManifest: BuiltinToolManifest = {
{
description:
'Write content to a specific file. Input should be the file path and content. Overwrites existing file or creates a new one.',
- humanIntervention: 'required',
+ humanIntervention: {
+ dynamic: {
+ default: 'never',
+ policy: 'required',
+ type: 'pathScopeAudit',
+ },
+ },
name: LocalSystemApiName.writeLocalFile,
parameters: {
properties: {
@@ -209,7 +250,13 @@ export const LocalSystemManifest: BuiltinToolManifest = {
{
description:
'Perform exact string replacements in files. Must read the file first before editing.',
- humanIntervention: 'required',
+ humanIntervention: {
+ dynamic: {
+ default: 'never',
+ policy: 'required',
+ type: 'pathScopeAudit',
+ },
+ },
name: LocalSystemApiName.editLocalFile,
parameters: {
properties: {
@@ -300,6 +347,13 @@ export const LocalSystemManifest: BuiltinToolManifest = {
{
description:
'Search for content within files using regex patterns. Supports various output modes and filtering options.',
+ humanIntervention: {
+ dynamic: {
+ default: 'never',
+ policy: 'required',
+ type: 'pathScopeAudit',
+ },
+ },
name: LocalSystemApiName.grepContent,
parameters: {
properties: {
@@ -344,14 +398,15 @@ export const LocalSystemManifest: BuiltinToolManifest = {
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',
},
+ 'scope': {
+ description:
+ 'Working directory scope. Limits the search to this directory. Defaults to the current working directory.',
+ type: 'string',
+ },
'type': {
description: 'File type to search (e.g. "js", "py", "rust")',
type: 'string',
@@ -364,15 +419,24 @@ export const LocalSystemManifest: BuiltinToolManifest = {
{
description:
'Find files matching glob patterns. Supports standard glob syntax like "**/*.js" or "src/**/*.ts".',
+ humanIntervention: {
+ dynamic: {
+ default: 'never',
+ policy: 'required',
+ type: 'pathScopeAudit',
+ },
+ },
name: LocalSystemApiName.globLocalFiles,
parameters: {
properties: {
- path: {
- description: 'The directory to search in (defaults to current working directory)',
+ pattern: {
+ description:
+ 'The glob pattern to match files against (e.g. "**/*.js", "src/**/*.ts"). Relative patterns are resolved against the scope.',
type: 'string',
},
- pattern: {
- description: 'The glob pattern to match files against (e.g. "**/*.js", "*.{ts,tsx}")',
+ scope: {
+ description:
+ 'Working directory scope. When `pattern` is relative, it is joined with this scope. Defaults to the current working directory.',
type: 'string',
},
},
diff --git a/packages/builtin-tool-local-system/src/systemRole.ts b/packages/builtin-tool-local-system/src/systemRole.ts
index 65f34cb962d..e61caa6a9e0 100644
--- a/packages/builtin-tool-local-system/src/systemRole.ts
+++ b/packages/builtin-tool-local-system/src/systemRole.ts
@@ -99,7 +99,7 @@ You have access to a set of tools to interact with the user's local file system:
- 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).
+ - 'path' (Optional): File or directory to search.
- '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.
@@ -108,7 +108,7 @@ You have access to a set of tools to interact with the user's local file system:
- '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).
+ - 'path' (Optional): Directory to search in.
Returns files sorted by modification time (most recent first).
</tool_usage_guidelines>
diff --git a/packages/builtin-tool-local-system/src/types.ts b/packages/builtin-tool-local-system/src/types.ts
index 5092e4fafd3..1d697ae4d98 100644
--- a/packages/builtin-tool-local-system/src/types.ts
+++ b/packages/builtin-tool-local-system/src/types.ts
@@ -1,12 +1,12 @@
-import type {
- GetCommandOutputResult,
- GlobFilesResult,
- GrepContentResult,
- KillCommandResult,
- LocalFileItem,
- LocalMoveFilesResultItem,
- LocalReadFileResult,
- RunCommandResult,
+import {
+ type GetCommandOutputResult,
+ type GlobFilesResult,
+ type GrepContentResult,
+ type KillCommandResult,
+ type LocalFileItem,
+ type LocalMoveFilesResultItem,
+ type LocalReadFileResult,
+ type RunCommandResult,
} from '@lobechat/electron-client-ipc';
export const LocalSystemIdentifier = 'lobe-local-system';
@@ -44,6 +44,8 @@ export interface FileResult {
export interface LocalFileSearchState {
/** Search engine used (e.g., 'mdfind', 'fd', 'find', 'fast-glob') */
engine?: string;
+ /** Resolved search directory after scope resolution */
+ resolvedPath?: string;
searchResults: LocalFileItem[];
}
@@ -91,11 +93,15 @@ export interface KillCommandState {
export interface GrepContentState {
message: string;
+ /** Resolved search path after scope resolution */
+ resolvedPath?: string;
result: GrepContentResult;
}
export interface GlobFilesState {
message: string;
+ /** Resolved full glob (path + pattern) after scope resolution. May contain glob metacharacters like `*` or `**`. */
+ resolvedPath?: string;
result: GlobFilesResult;
}
diff --git a/packages/builtin-tool-local-system/src/utils/__tests__/path.test.ts b/packages/builtin-tool-local-system/src/utils/__tests__/path.test.ts
new file mode 100644
index 00000000000..3e87800250a
--- /dev/null
+++ b/packages/builtin-tool-local-system/src/utils/__tests__/path.test.ts
@@ -0,0 +1,142 @@
+import { describe, expect, it } from 'vitest';
+
+import { normalizePathForScope, resolveArgsWithScope, resolvePathWithScope } from '../path';
+
+describe('normalizePathForScope', () => {
+ it('should normalize a simple absolute path', () => {
+ expect(normalizePathForScope('/Users/me/project')).toBe('/Users/me/project');
+ });
+
+ it('should strip trailing slash', () => {
+ expect(normalizePathForScope('/Users/me/project/')).toBe('/Users/me/project');
+ });
+
+ it('should keep root as /', () => {
+ expect(normalizePathForScope('/')).toBe('/');
+ });
+
+ it('should normalize .. segments', () => {
+ expect(normalizePathForScope('/Users/me/project/../other')).toBe('/Users/me/other');
+ });
+
+ it('should convert backslashes to forward slashes', () => {
+ expect(normalizePathForScope('C:\\Users\\me\\project')).toBe('c:/Users/me/project');
+ });
+
+ it('should normalize drive letter to lowercase', () => {
+ expect(normalizePathForScope('D:/workspace')).toBe('d:/workspace');
+ });
+
+ it('should treat empty string as root', () => {
+ expect(normalizePathForScope('')).toBe('/');
+ });
+
+ it('should prepend slash to relative-looking path', () => {
+ expect(normalizePathForScope('foo/bar')).toBe('/foo/bar');
+ });
+});
+
+describe('resolvePathWithScope', () => {
+ it('should return scope when no inputPath is provided', () => {
+ expect(resolvePathWithScope(undefined, '/workspace')).toBe('/workspace');
+ });
+
+ it('should return inputPath as-is when no scope is provided', () => {
+ expect(resolvePathWithScope('/some/path', undefined)).toBe('/some/path');
+ });
+
+ it('should return undefined when both are undefined', () => {
+ expect(resolvePathWithScope(undefined, undefined)).toBeUndefined();
+ });
+
+ it('should return absolute inputPath as-is, ignoring scope', () => {
+ expect(resolvePathWithScope('/absolute/path', '/workspace')).toBe('/absolute/path');
+ });
+
+ it('should join relative inputPath with scope', () => {
+ expect(resolvePathWithScope('src/index.ts', '/workspace')).toBe('/workspace/src/index.ts');
+ });
+
+ it('should join relative path with dots', () => {
+ expect(resolvePathWithScope('../other/file.ts', '/workspace/project')).toBe(
+ '/workspace/other/file.ts',
+ );
+ });
+
+ it('should handle scope with trailing slash', () => {
+ expect(resolvePathWithScope('file.ts', '/workspace/')).toBe('/workspace/file.ts');
+ });
+
+ it('should return empty-string inputPath joined with scope', () => {
+ expect(resolvePathWithScope('', '/workspace')).toBe('/workspace');
+ });
+
+ it('should join glob pattern with scope', () => {
+ expect(resolvePathWithScope('**/*.ts', '/workspace')).toBe('/workspace/**/*.ts');
+ });
+
+ it('should join relative glob pattern with scope', () => {
+ expect(resolvePathWithScope('src/**/*.tsx', '/workspace')).toBe('/workspace/src/**/*.tsx');
+ });
+
+ it('should return absolute glob pattern as-is', () => {
+ expect(resolvePathWithScope('/absolute/**/*.ts', '/workspace')).toBe('/absolute/**/*.ts');
+ });
+});
+
+describe('resolveArgsWithScope', () => {
+ it('should resolve path field from scope when path is not provided', () => {
+ const args = { scope: '/workspace' };
+ const result = resolveArgsWithScope(args, 'path');
+ expect((result as any).path).toBe('/workspace');
+ });
+
+ it('should resolve relative path field with scope', () => {
+ const args = { path: 'src/file.ts', scope: '/workspace' };
+ const result = resolveArgsWithScope(args, 'path');
+ expect(result.path).toBe('/workspace/src/file.ts');
+ });
+
+ it('should leave absolute path unchanged', () => {
+ const args = { path: '/absolute/file.ts', scope: '/workspace' };
+ const result = resolveArgsWithScope(args, 'path');
+ expect(result).toBe(args); // same reference, no copy
+ });
+
+ it('should use fallbackScope when args.scope is not provided', () => {
+ const args = { path: 'src/file.ts' } as { scope?: string; path: string };
+ const result = resolveArgsWithScope(args, 'path', '/fallback');
+ expect(result.path).toBe('/fallback/src/file.ts');
+ });
+
+ it('should prefer args.scope over fallbackScope', () => {
+ const args = { scope: '/explicit', path: 'file.ts' };
+ const result = resolveArgsWithScope(args, 'path', '/fallback');
+ expect(result.path).toBe('/explicit/file.ts');
+ });
+
+ it('should return same reference when nothing changes', () => {
+ const args = { path: '/absolute/path' } as { scope?: string; path: string };
+ const result = resolveArgsWithScope(args, 'path');
+ expect(result).toBe(args);
+ });
+
+ it('should work with directory field', () => {
+ const args = { directory: 'subdir', scope: '/workspace' };
+ const result = resolveArgsWithScope(args, 'directory');
+ expect((result as any).directory).toBe('/workspace/subdir');
+ });
+
+ it('should fill directory from scope when directory is undefined', () => {
+ const args = { scope: '/workspace' };
+ const result = resolveArgsWithScope(args, 'directory');
+ expect((result as any).directory).toBe('/workspace');
+ });
+
+ it('should not mutate the original args', () => {
+ const args = { path: 'relative', scope: '/workspace' };
+ const originalPath = args.path;
+ resolveArgsWithScope(args, 'path');
+ expect(args.path).toBe(originalPath);
+ });
+});
diff --git a/packages/builtin-tool-local-system/src/utils/path.ts b/packages/builtin-tool-local-system/src/utils/path.ts
new file mode 100644
index 00000000000..bc5f8f495ad
--- /dev/null
+++ b/packages/builtin-tool-local-system/src/utils/path.ts
@@ -0,0 +1,57 @@
+import path from 'path-browserify-esm';
+
+const normalizeDriveLetter = (input: string): string =>
+ input.replace(/^[A-Z]:/i, (match) => match.toLowerCase());
+
+const toNormalizedAbsolute = (input: string): string => {
+ const trimmed = input.trim();
+ const withPosixSeparators = trimmed.replaceAll('\\', '/');
+ const withNormalizedDrive = normalizeDriveLetter(withPosixSeparators);
+
+ if (withNormalizedDrive === '') return '/';
+
+ const hasDriveLetter = /^[A-Z]:/i.test(withNormalizedDrive);
+ const hasLeadingSlash = withNormalizedDrive.startsWith('/');
+ const absolutePath =
+ hasDriveLetter || hasLeadingSlash ? withNormalizedDrive : `/${withNormalizedDrive}`;
+
+ return path.normalize(absolutePath);
+};
+
+export const normalizePathForScope = (input: string): string => {
+ const normalized = toNormalizedAbsolute(input);
+ return normalized.length > 1 && normalized.endsWith('/') ? normalized.slice(0, -1) : normalized;
+};
+
+/**
+ * Resolve a path against a scope (CWD).
+ * - No path provided → use scope as default
+ * - Absolute path → use as-is, ignore scope
+ * - Relative path → join with scope
+ * - No scope → return path as-is
+ */
+export const resolvePathWithScope = (
+ inputPath: string | undefined,
+ scope: string | undefined,
+): string | undefined => {
+ if (!scope) return inputPath;
+ if (!inputPath) return scope;
+ if (path.isAbsolute(inputPath)) return inputPath;
+ return path.join(scope, inputPath);
+};
+
+/**
+ * Resolve a `scope`-bearing args object, filling the target path field from scope.
+ * Returns a shallow copy only if the path field was actually changed.
+ */
+export const resolveArgsWithScope = <T extends { scope?: string }>(
+ args: T,
+ pathField: string,
+ fallbackScope?: string,
+): T => {
+ const scope = args.scope || fallbackScope;
+ const currentPath = (args as Record<string, any>)[pathField] as string | undefined;
+ const resolved = resolvePathWithScope(currentPath, scope);
+ if (resolved === currentPath) return args;
+ return { ...args, [pathField]: resolved };
+};
diff --git a/packages/builtin-tool-local-system/vitest.config.mts b/packages/builtin-tool-local-system/vitest.config.mts
new file mode 100644
index 00000000000..4ac6027d578
--- /dev/null
+++ b/packages/builtin-tool-local-system/vitest.config.mts
@@ -0,0 +1,7 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ environment: 'node',
+ },
+});
diff --git a/packages/context-engine/src/engine/tools/types.ts b/packages/context-engine/src/engine/tools/types.ts
index 998199f82d3..013da5683e9 100644
--- a/packages/context-engine/src/engine/tools/types.ts
+++ b/packages/context-engine/src/engine/tools/types.ts
@@ -1,4 +1,4 @@
-import type { HumanInterventionConfig } from '@/types/index';
+import type { ExtendedHumanInterventionConfig } from '@/types/index';
export interface LobeChatPluginApi {
description: string;
@@ -14,7 +14,7 @@ export interface LobeChatPluginApi {
* - 'always' - always require intervention
* - [{ match: { command: "git add:*" }, policy: "never" }, { policy: "always" }]
*/
- humanIntervention?: HumanInterventionConfig;
+ humanIntervention?: ExtendedHumanInterventionConfig;
name: string;
parameters: Record<string, any>;
url?: string;
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index b2649116718..8b030eaf982 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -1,4 +1,3 @@
-/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
// Define types for local file operations
export interface LocalFileItem {
contentType?: string;
@@ -155,6 +154,9 @@ export interface LocalSearchFilesParams {
liveUpdate?: boolean;
modifiedAfter?: string;
modifiedBefore?: string;
+
+ /** Working directory scope. When `directory` is not specified, used as the default search location. */
+ scope?: string;
sortBy?: 'name' | 'date' | 'size';
sortDirection?: 'asc' | 'desc';
}
@@ -222,6 +224,8 @@ export interface GrepContentParams {
'output_mode'?: 'content' | 'files_with_matches' | 'count';
'path'?: string;
'pattern': string;
+ /** Working directory scope. When `path` is not specified, used as the default search location. */
+ 'scope'?: string;
/** Preferred search tool: 'rg' | 'ag' | 'grep' */
'tool'?: 'rg' | 'ag' | 'grep';
'type'?: string;
@@ -238,8 +242,9 @@ export interface GrepContentResult {
// Glob types
export interface GlobFilesParams {
- path?: string;
pattern: string;
+ /** Working directory scope. When `pattern` is relative, it is joined with this scope. Defaults to the current working directory. */
+ scope?: string;
}
export interface GlobFilesResult {
diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.ts
index 86df9cc5a19..59aa6500c4a 100644
--- a/packages/types/src/tool/builtin.ts
+++ b/packages/types/src/tool/builtin.ts
@@ -1,8 +1,8 @@
-import type { ReactNode } from 'react';
+import { type ReactNode } from 'react';
import { z } from 'zod';
-import type { RuntimeStepContext } from '../stepContext';
-import type { HumanInterventionConfig, HumanInterventionPolicy } from './intervention';
+import { type RuntimeStepContext } from '../stepContext';
+import { type HumanInterventionConfig, type HumanInterventionPolicy } from './intervention';
import { HumanInterventionConfigSchema, HumanInterventionPolicySchema } from './intervention';
interface Meta {
@@ -53,6 +53,86 @@ export type RenderDisplayControl = 'alwaysExpand' | 'collapsed' | 'expand';
export const RenderDisplayControlSchema = z.enum(['collapsed', 'expand', 'alwaysExpand']);
+/**
+ * Dynamic intervention resolver function type
+ * Receives tool args and state metadata to determine if condition is met
+ * @returns true if intervention is required, false otherwise
+ */
+export type DynamicInterventionResolver = (
+ toolArgs: Record<string, any>,
+ metadata?: Record<string, any>,
+) => boolean;
+
+/**
+ * Global intervention audit configuration
+ * Global audits run for EVERY tool call, not just tools with dynamic config.
+ * They are evaluated before per-tool dynamic audits in the intervention chain.
+ */
+export interface GlobalInterventionAuditConfig {
+ /**
+ * Policy to apply when audit condition is met (returns true)
+ * - 'always': cannot be bypassed by auto-run; in headless mode the tool is skipped entirely
+ * - 'required': requires intervention but can be bypassed by auto-run
+ * @default 'always'
+ */
+ policy?: HumanInterventionPolicy;
+
+ /**
+ * The audit function, reuses DynamicInterventionResolver signature
+ */
+ resolver: DynamicInterventionResolver;
+
+ /**
+ * Unique type identifier for this global audit
+ */
+ type: string;
+}
+
+/**
+ * Dynamic intervention configuration
+ * Used to dynamically determine intervention policy based on runtime context
+ *
+ * The resolver is referenced by type identifier and looked up from
+ * the dynamicInterventionAudits registry at runtime.
+ */
+export interface DynamicInterventionConfig {
+ /**
+ * Default policy when resolver returns false or no resolver is available
+ * @default 'never'
+ */
+ default?: HumanInterventionPolicy;
+
+ /**
+ * Policy to apply when resolver condition is met
+ * @default 'always'
+ */
+ policy?: HumanInterventionPolicy;
+
+ /**
+ * Resolver type identifier for external resolver lookup
+ * The resolver function is registered in dynamicInterventionAudits
+ */
+ type: string;
+}
+
+export const DynamicInterventionConfigSchema = z.object({
+ default: HumanInterventionPolicySchema.optional(),
+ policy: HumanInterventionPolicySchema.optional(),
+ type: z.string(),
+});
+
+/**
+ * Extended human intervention config that supports dynamic evaluation
+ */
+export type ExtendedHumanInterventionConfig =
+ | HumanInterventionConfig
+ | { dynamic: DynamicInterventionConfig };
+
+export const ExtendedHumanInterventionConfigSchema = z.union([
+ HumanInterventionConfigSchema,
+ z.object({ dynamic: DynamicInterventionConfigSchema }),
+]);
+
export interface LobeChatPluginApi {
description: string;
/**
@@ -60,14 +140,17 @@ export interface LobeChatPluginApi {
* Controls when and how the tool requires human approval/selection
*
* Can be either:
- * - Simple: A policy string ('never', 'always', 'first')
+ * - Simple: A policy string ('never', 'always', 'required')
* - Complex: Array of rules for parameter-level control
+ * - Dynamic: { dynamic: DynamicInterventionConfig } for runtime evaluation
*
* Examples:
* - 'always' - always require intervention
* - [{ match: { command: "git add:*" }, policy: "never" }, { policy: "always" }]
+ * - { dynamic: { default: 'never', policy: 'required', type: 'exampleResolver' } } - exampleResolver should register in `GeneralChatAgent.dynamicInterventionAudits`
+ *
*/
- humanIntervention?: HumanInterventionConfig;
+ humanIntervention?: ExtendedHumanInterventionConfig;
name: string;
parameters: Record<string, any>;
/**
@@ -84,7 +167,7 @@ export interface LobeChatPluginApi {
export const LobeChatPluginApiSchema = z.object({
description: z.string(),
- humanIntervention: HumanInterventionConfigSchema.optional(),
+ humanIntervention: ExtendedHumanInterventionConfigSchema.optional(),
name: z.string(),
parameters: z.record(z.string(), z.any()),
renderDisplayControl: RenderDisplayControlSchema.optional(),
@@ -121,7 +204,7 @@ export interface BuiltinToolManifest {
export const BuiltinToolManifestSchema = z.object({
api: z.array(LobeChatPluginApiSchema),
- humanIntervention: HumanInterventionPolicySchema.optional(),
+ humanIntervention: ExtendedHumanInterventionConfigSchema.optional(),
identifier: z.string(),
meta: MetaSchema,
systemRole: z.string(),
@@ -357,6 +440,12 @@ export interface BuiltinToolContext {
* Used by tools that need to create messages or operations within a topic
*/
topicId?: string | null;
+
+ /**
+ * The working directory configured for file operations
+ * When set, file operations should be restricted to this directory
+ */
+ workingDirectory?: string;
}
/**
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/SecurityBlacklistWarning.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/SecurityBlacklistWarning.tsx
new file mode 100644
index 00000000000..bbbaa136c4e
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/SecurityBlacklistWarning.tsx
@@ -0,0 +1,37 @@
+import { DEFAULT_SECURITY_BLACKLIST, InterventionChecker } from '@lobechat/agent-runtime';
+import { Alert, Flexbox } from '@lobehub/ui';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface SecurityBlacklistWarningProps {
+ args: Record<string, any>;
+}
+
+const SecurityBlacklistWarning = memo<SecurityBlacklistWarningProps>(({ args }) => {
+ const { t } = useTranslation('tool');
+
+ const securityCheck = useMemo(
+ () => InterventionChecker.checkSecurityBlacklist(DEFAULT_SECURITY_BLACKLIST, args),
+ [args],
+ );
+
+ if (!securityCheck.blocked) return null;
+
+ return (
+ <Alert
+ showIcon
+ title={t('localFiles.securityBlacklist.warning')}
+ type="error"
+ variant="borderless"
+ description={
+ <Flexbox gap={4} style={{ fontSize: 12 }}>
+ <div>{securityCheck.reason ? t(securityCheck.reason as any) : undefined}</div>
+ </Flexbox>
+ }
+ />
+ );
+});
+
+SecurityBlacklistWarning.displayName = 'SecurityBlacklistWarning';
+
+export default SecurityBlacklistWarning;
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx
index 587f28a8154..ae0e1c9db79 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx
@@ -1,6 +1,6 @@
import { safeParseJSON } from '@lobechat/utils';
import { Flexbox } from '@lobehub/ui';
-import { memo, Suspense, useCallback, useRef, useState } from 'react';
+import { memo, Suspense, useCallback, useMemo, useRef, useState } from 'react';
import { useUserStore } from '@/store/user';
import { toolInterventionSelectors } from '@/store/user/selectors';
@@ -12,6 +12,7 @@ import ApprovalActions from './ApprovalActions';
import Fallback from './Fallback';
import KeyValueEditor from './KeyValueEditor';
import ModeSelector from './ModeSelector';
+import SecurityBlacklistWarning from './SecurityBlacklistWarning';
export type ApprovalMode = 'auto-run' | 'allow-list' | 'manual';
@@ -82,6 +83,8 @@ const Intervention = memo<InterventionProps>(
[toolCallId, updatePluginArguments],
);
+ const parsedArgs = useMemo(() => safeParseJSON(requestArgs || '') ?? {}, [requestArgs]);
+
const BuiltinToolInterventionRender = getBuiltinIntervention(identifier, apiName);
if (BuiltinToolInterventionRender) {
@@ -89,7 +92,7 @@ const Intervention = memo<InterventionProps>(
return (
<Suspense fallback={<Arguments arguments={requestArgs} />}>
<KeyValueEditor
- initialValue={safeParseJSON(requestArgs || '')}
+ initialValue={parsedArgs}
onCancel={handleCancel}
onFinish={handleFinish}
/>
@@ -98,9 +101,10 @@ const Intervention = memo<InterventionProps>(
return (
<Flexbox gap={12}>
+ <SecurityBlacklistWarning args={parsedArgs} />
<BuiltinToolInterventionRender
apiName={apiName}
- args={safeParseJSON(requestArgs || '')}
+ args={parsedArgs}
identifier={identifier}
messageId={id}
registerBeforeApprove={registerBeforeApprove}
@@ -122,13 +126,16 @@ const Intervention = memo<InterventionProps>(
}
return (
- <Fallback
- apiName={apiName}
- id={id}
- identifier={identifier}
- requestArgs={requestArgs}
- toolCallId={toolCallId}
- />
+ <Flexbox gap={12}>
+ <SecurityBlacklistWarning args={parsedArgs} />
+ <Fallback
+ apiName={apiName}
+ id={id}
+ identifier={identifier}
+ requestArgs={requestArgs}
+ toolCallId={toolCallId}
+ />
+ </Flexbox>
);
},
);
diff --git a/src/features/ModelSwitchPanel/components/List/index.tsx b/src/features/ModelSwitchPanel/components/List/index.tsx
index 463faa83f91..68c90d7a646 100644
--- a/src/features/ModelSwitchPanel/components/List/index.tsx
+++ b/src/features/ModelSwitchPanel/components/List/index.tsx
@@ -83,7 +83,6 @@ export const List: FC<ListProps> = ({
flex={1}
style={{
height: listHeight,
- paddingBlock: groupMode === 'byModel' ? 8 : 0,
}}
>
<TooltipGroup>
diff --git a/src/locales/default/tool.ts b/src/locales/default/tool.ts
index 3afefb6deee..de7d578fc5f 100644
--- a/src/locales/default/tool.ts
+++ b/src/locales/default/tool.ts
@@ -89,6 +89,10 @@ export default {
'localFiles.editFile.replaceFirst': 'Replace first occurrence only',
'localFiles.file': 'File',
'localFiles.folder': 'Folder',
+ 'localFiles.globFiles.pattern': 'Pattern',
+ 'localFiles.grepContent.glob': 'File filter',
+ 'localFiles.grepContent.pattern': 'Search pattern',
+ 'localFiles.grepContent.type': 'File type',
'localFiles.moveFiles.itemsMoved': '{{count}} item(s) moved:',
'localFiles.moveFiles.itemsMoved_one': '{{count}} item moved:',
'localFiles.moveFiles.itemsMoved_other': '{{count}} items moved:',
@@ -98,11 +102,48 @@ export default {
'localFiles.open': 'Open',
'localFiles.openFile': 'Open File',
'localFiles.openFolder': 'Open Folder',
+ 'localFiles.outOfScope.requestedPaths': 'Requested Paths',
+ 'localFiles.outOfScope.warning':
+ 'Warning: The following path(s) are outside the configured working directory. Please confirm you want to allow access.',
+ 'localFiles.outOfScope.workingDirectory': 'Working Directory',
+ 'localFiles.securityBlacklist.warning':
+ 'Security Alert: This operation has been flagged by security rules and requires your explicit approval.',
+ 'securityBlacklist.awsCredentials': 'Accessing AWS credentials can leak cloud access keys',
+ 'securityBlacklist.browserCredentials': 'Accessing browser credential storage may leak passwords',
+ 'securityBlacklist.chownSystemDirs': 'Changing file ownership of system directories is dangerous',
+ 'securityBlacklist.ddDiskWrite': 'Writing random data to disk devices can destroy data',
+ 'securityBlacklist.directMemoryAccess': 'Direct memory access is extremely dangerous',
+ 'securityBlacklist.disableFirewall': 'Disabling firewall exposes system to attacks',
+ 'securityBlacklist.dockerConfig': 'Reading Docker config may expose registry credentials',
+ 'securityBlacklist.envFiles': 'Reading .env files may leak sensitive credentials and API keys',
+ 'securityBlacklist.etcPasswd': 'Modifying /etc/passwd could lock you out of the system',
+ 'securityBlacklist.formatPartition': 'Formatting system partitions will destroy data',
+ 'securityBlacklist.forkBomb': 'Fork bomb can crash the system',
+ 'securityBlacklist.gcpCredentials': 'Reading GCP credentials may leak cloud service account keys',
+ 'securityBlacklist.gitCredentials': 'Reading Git credentials file may leak access tokens',
+ 'securityBlacklist.historyFiles':
+ 'Reading history files may expose sensitive commands and credentials',
+ 'securityBlacklist.kernelParams':
+ 'Modifying kernel parameters without understanding can crash the system',
+ 'securityBlacklist.kubeConfig': 'Reading Kubernetes config may expose cluster credentials',
+ 'securityBlacklist.npmrc': 'Reading npm token file may expose package registry credentials',
+ 'securityBlacklist.removeSystemPackages':
+ 'Removing essential system packages can break the system',
+ 'securityBlacklist.rmForceRecursive':
+ 'Force recursive deletion without specific target is too dangerous',
+ 'securityBlacklist.rmHomeDir': 'Recursive deletion of home directory is extremely dangerous',
+ 'securityBlacklist.rmRootDir': 'Recursive deletion of root directory will destroy the system',
+ 'securityBlacklist.sshConfig': 'Changing SSH configuration could lock you out',
+ 'securityBlacklist.sshPrivateKeys': 'Reading SSH private keys can compromise system security',
+ 'securityBlacklist.sudoers': 'Modifying sudoers file without proper validation is dangerous',
+ 'securityBlacklist.suidShells': 'Setting SUID on shells or interpreters is a security risk',
'localFiles.read.more': 'View More',
'localFiles.readFile': 'Read File',
+ 'localFiles.readFile.lineRange': 'Lines {{start}} - {{end}}',
'localFiles.readFileError': 'Failed to read file, please check if the file path is correct',
'localFiles.readFiles': 'Read Files',
'localFiles.readFilesError': 'Failed to read files, please check if the file path is correct',
+ 'localFiles.searchFiles.keywords': 'Keywords',
'localFiles.writeFile.characters': 'characters',
'localFiles.writeFile.preview': 'Content Preview',
'localFiles.writeFile.truncated': 'truncated',
diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.ts
index 53808af4190..03a06062896 100644
--- a/src/server/services/agentRuntime/AgentRuntimeService.ts
+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts
@@ -19,6 +19,7 @@ import { QueueService } from '@/server/services/queue';
import { LocalQueueServiceImpl } from '@/server/services/queue/impls';
import { ToolExecutionService } from '@/server/services/toolExecution';
import { BuiltinToolsExecutor } from '@/server/services/toolExecution/builtin';
+import { dynamicInterventionAudits } from '@/tools/dynamicInterventionAudits';
import {
type AgentExecutionParams,
@@ -244,6 +245,7 @@ export class AgentRuntimeService {
// need be removed
modelRuntimeConfig,
userId,
+ workingDirectory: agentConfig?.chatConfig?.localSystem?.workingDirectory,
...appContext,
},
// modelRuntimeConfig at state level for executor fallback
@@ -834,6 +836,7 @@ export class AgentRuntimeService {
compressionConfig: {
enabled: metadata?.agentConfig?.chatConfig?.enableContextCompression ?? true,
},
+ dynamicInterventionAudits,
modelRuntimeConfig: metadata?.modelRuntimeConfig,
operationId,
userId: metadata?.userId,
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index f1318270797..7c3dc9497fb 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -1,4 +1,3 @@
-/* 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 {
type AgentRuntimeContext,
@@ -37,6 +36,7 @@ import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-pag
import { type StoreSetter } from '@/store/types';
import { toolInterventionSelectors } from '@/store/user/selectors';
import { getUserStoreState } from '@/store/user/store';
+import { dynamicInterventionAudits } from '@/tools/dynamicInterventionAudits';
import { markdownToTxt } from '@/utils/markdownToTxt';
import { topicSelectors } from '../../../selectors';
@@ -182,6 +182,10 @@ export class StreamingExecutorActionImpl {
provider: agentConfigData.provider!,
};
+ const topicWorkingDirectory = topicSelectors.currentTopicWorkingDirectory(this.#get());
+ const agentWorkingDirectory = agentSelectors.currentAgentWorkingDirectory(getAgentStoreState());
+ const workingDirectory = topicWorkingDirectory ?? agentWorkingDirectory;
+
// Create initial state or use provided state
const state =
initialState ||
@@ -192,6 +196,7 @@ export class StreamingExecutorActionImpl {
sessionId: agentId,
threadId,
topicId,
+ workingDirectory,
},
modelRuntimeConfig,
operationId: operationId ?? agentId,
@@ -666,6 +671,7 @@ export class StreamingExecutorActionImpl {
compressionConfig: {
enabled: agentConfigData.chatConfig?.enableContextCompression ?? true, // Default to enabled
},
+ dynamicInterventionAudits,
operationId: `${messageKey}/${params.parentMessageId}`,
modelRuntimeConfig,
});
diff --git a/src/tools/dynamicInterventionAudits.ts b/src/tools/dynamicInterventionAudits.ts
new file mode 100644
index 00000000000..cd5fb3b5e4d
--- /dev/null
+++ b/src/tools/dynamicInterventionAudits.ts
@@ -0,0 +1,6 @@
+import { pathScopeAudit } from '@lobechat/builtin-tool-local-system';
+import { type DynamicInterventionResolver } from '@lobechat/types';
+
+export const dynamicInterventionAudits: Record<string, DynamicInterventionResolver> = {
+ pathScopeAudit,
+};