🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(builtin-tool-local-system): skip intervention for safe paths like /tmp (#13232)
Innei84674b1e1064
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.tsindex 2874d2fc555..1908d52cd1d 100644--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts@@ -1,8 +1,10 @@import { constants } from 'node:fs';-import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises';+import { access, mkdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';import path from 'node:path';import {+ type AuditSafePathsParams,+ type AuditSafePathsResult,type EditLocalFileParams,type EditLocalFileResult,type GlobFilesParams,@@ -52,6 +54,72 @@ import { ControllerModule, IpcMethod } from './index';// Create loggerconst logger = createLogger('controllers:LocalFileCtr');+const SAFE_PATH_PREFIXES = ['/tmp', '/var/tmp'] as const;++const normalizeAbsolutePath = (inputPath: string): string =>+ path.normalize(path.isAbsolute(inputPath) ? inputPath : `/${inputPath}`);++const resolvePathWithScope = (inputPath: string, scope: string): string =>+ path.isAbsolute(inputPath) ? inputPath : path.join(scope, inputPath);++const isWithinSafePathPrefixes = (targetPath: string, prefixes: readonly string[]): boolean =>+ prefixes.some((prefix) => targetPath === prefix || targetPath.startsWith(`${prefix}${path.sep}`));++const resolveNearestExistingRealPath = async (targetPath: string): Promise<string | undefined> => {+ let currentPath = targetPath;++ while (true) {+ try {+ await access(currentPath, constants.F_OK);+ return normalizeAbsolutePath(await realpath(currentPath));+ } catch {+ const parentPath = path.dirname(currentPath);+ if (parentPath === currentPath) return undefined;+ currentPath = parentPath;+ }+ }+};++const resolveSafePathRealPrefixes = async (): Promise<string[]> => {+ const prefixes = new Set<string>(SAFE_PATH_PREFIXES);++ for (const safePrefix of SAFE_PATH_PREFIXES) {+ try {+ prefixes.add(normalizeAbsolutePath(await realpath(safePrefix)));+ } catch {+ // Keep the lexical prefix if the platform does not expose this directory.+ }+ }++ return [...prefixes];+};++const areAllPathsSafeOnDisk = async (+ paths: string[],+ resolveAgainstScope: string,+): Promise<boolean> => {+ if (paths.length === 0) return false;++ const safeRealPrefixes = await resolveSafePathRealPrefixes();++ for (const currentPath of paths) {+ const normalizedPath = normalizeAbsolutePath(+ resolvePathWithScope(currentPath, resolveAgainstScope),+ );++ if (!isWithinSafePathPrefixes(normalizedPath, SAFE_PATH_PREFIXES)) {+ return false;+ }++ const realPath = await resolveNearestExistingRealPath(normalizedPath);+ if (!realPath || !isWithinSafePathPrefixes(realPath, safeRealPrefixes)) {+ return false;+ }+ }++ return true;+};+export default class LocalFileCtr extends ControllerModule {static override readonly groupName = 'localSystem';private get searchService() {@@ -240,6 +308,18 @@ export default class LocalFileCtr extends ControllerModule {return writeLocalFile({ content, path: filePath });}+ @IpcMethod()+ async auditSafePaths({+ paths,+ resolveAgainstScope,+ }: AuditSafePathsParams): Promise<AuditSafePathsResult> {+ logger.debug('Auditing safe paths', { count: paths.length, resolveAgainstScope });++ return {+ allSafe: await areAllPathsSafeOnDisk(paths, resolveAgainstScope),+ };+ }+@IpcMethod()async handlePrepareSkillDirectory({forceRefresh,diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.tsindex 0f38c9f68d3..0105de558c4 100644--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.test.ts@@ -45,6 +45,7 @@ vi.mock('node:fs/promises', () => ({mkdir: vi.fn(),readFile: vi.fn(),readdir: vi.fn(),+ realpath: vi.fn(),rename: vi.fn(),rm: vi.fn(),stat: vi.fn(),@@ -301,6 +302,46 @@ describe('LocalFileCtr', () => {});});+ describe('auditSafePaths', () => {+ it('should treat real temporary paths as safe', async () => {+ vi.mocked(mockFsPromises.access).mockResolvedValue(undefined);+ vi.mocked(mockFsPromises.realpath).mockImplementation(async (targetPath: string) => {+ if (targetPath === '/tmp') return '/private/tmp';+ if (targetPath === '/var/tmp') return '/private/var/tmp';+ if (targetPath === '/tmp/out') return '/private/tmp/out';+ return targetPath;+ });++ const result = await localFileCtr.auditSafePaths({+ paths: ['/tmp/out'],+ resolveAgainstScope: '/Users/me/project',+ });++ expect(result).toEqual({ allSafe: true });+ });++ it('should reject safe-path candidates whose real target escapes the temporary roots', async () => {+ vi.mocked(mockFsPromises.access).mockImplementation(async (targetPath: string) => {+ if (targetPath === '/tmp/out/config') {+ throw new Error('ENOENT');+ }+ });+ vi.mocked(mockFsPromises.realpath).mockImplementation(async (targetPath: string) => {+ if (targetPath === '/tmp') return '/private/tmp';+ if (targetPath === '/var/tmp') return '/private/var/tmp';+ if (targetPath === '/tmp/out') return '/Users/me/.ssh';+ return targetPath;+ });++ const result = await localFileCtr.auditSafePaths({+ paths: ['/tmp/out/config'],+ resolveAgainstScope: '/Users/me/project',+ });++ expect(result).toEqual({ allSafe: false });+ });+ });+describe('handlePrepareSkillDirectory', () => {it('should download and extract a skill zip into a local cache directory', async () => {const zipped = zipSync({diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex 0d82f535629..c5b09110c98 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -102,18 +102,19 @@ export class GeneralChatAgent implements Agent {config: ExtendedHumanInterventionConfig | undefined,toolArgs: Record<string, any>,metadata?: Record<string, any>,- ): HumanInterventionPolicy | undefined {+ ): Promise<HumanInterventionPolicy | undefined> {if (!this.isDynamicInterventionConfig(config)) {- return undefined;+ return Promise.resolve(undefined);}const { dynamic } = config;const resolver = this.config.dynamicInterventionAudits?.[dynamic.type];- if (!resolver) return dynamic.default ?? 'never';+ if (!resolver) return Promise.resolve(dynamic.default ?? 'never');- const shouldIntervene = resolver(toolArgs, metadata);- return shouldIntervene ? (dynamic.policy ?? 'always') : (dynamic.default ?? 'never');+ return Promise.resolve(resolver(toolArgs, metadata)).then((shouldIntervene) =>+ shouldIntervene ? (dynamic.policy ?? 'always') : (dynamic.default ?? 'never'),+ );}/**@@ -121,10 +122,10 @@ export class GeneralChatAgent implements Agent {* Combines user's global config with tool's own config* Returns [toolsNeedingIntervention, toolsToExecute]*/- private checkInterventionNeeded(+ private async checkInterventionNeeded(toolsCalling: ChatToolPayload[],state: AgentState,- ): [ChatToolPayload[], ChatToolPayload[]] {+ ): Promise<[ChatToolPayload[], ChatToolPayload[]]> {const toolsNeedingIntervention: ChatToolPayload[] = [];const toolsToExecute: ChatToolPayload[] = [];@@ -158,7 +159,7 @@ export class GeneralChatAgent implements Agent {let globalPolicy: HumanInterventionPolicy = 'always';for (const globalResolver of globalResolvers) {- if (globalResolver.resolver(toolArgs, resolverMetadata)) {+ if (await globalResolver.resolver(toolArgs, resolverMetadata)) {globalBlocked = true;globalPolicy = globalResolver.policy ?? 'always';break;@@ -185,7 +186,7 @@ export class GeneralChatAgent implements Agent {// Phase 3: Per-tool dynamic resolverconst config = this.getToolInterventionConfig(toolCalling, state);const isDynamicConfig = this.isDynamicInterventionConfig(config);- const dynamicPolicy = this.resolveDynamicPolicy(config, toolArgs, state.metadata);+ const dynamicPolicy = await this.resolveDynamicPolicy(config, toolArgs, state.metadata);const staticConfig = isDynamicConfig? undefined: (config as HumanInterventionConfig | undefined);@@ -420,7 +421,7 @@ export class GeneralChatAgent implements Agent {if (hasToolsCalling && toolsCalling && toolsCalling.length > 0) {// Check which tools need human intervention- const [toolsNeedingIntervention, toolsToExecute] = this.checkInterventionNeeded(+ const [toolsNeedingIntervention, toolsToExecute] = await this.checkInterventionNeeded(toolsCalling,state,);diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.tsindex b513ed28d5d..e65dede5069 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -1456,7 +1456,7 @@ describe('GeneralChatAgent', () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },dynamicInterventionAudits: {- pathScopeAudit: (toolArgs, metadata) => {+ pathScopeAudit: async (toolArgs, metadata) => {const workingDirectory = metadata?.workingDirectory as string | undefined;if (!workingDirectory) return false;const path = toolArgs.path as string;@@ -1517,7 +1517,7 @@ describe('GeneralChatAgent', () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },dynamicInterventionAudits: {- pathScopeAudit: (toolArgs, metadata) => {+ pathScopeAudit: async (toolArgs, metadata) => {const workingDirectory = metadata?.workingDirectory as string | undefined;if (!workingDirectory) return false;const path = toolArgs.path as string;@@ -1576,6 +1576,68 @@ describe('GeneralChatAgent', () => {]);});+ it('should await async dynamic intervention resolvers', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ dynamicInterventionAudits: {+ pathScopeAudit: async (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 check intervention at API level when configured', async () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },@@ -2028,7 +2090,7 @@ describe('GeneralChatAgent', () => {const customResolver: GlobalInterventionAuditConfig = {type: 'customBlocker',policy: 'always',- resolver: (toolArgs) => toolArgs.dangerous === true,+ resolver: async (toolArgs) => toolArgs.dangerous === true,};const agent = new GeneralChatAgent({@@ -2073,7 +2135,7 @@ describe('GeneralChatAgent', () => {const customResolver: GlobalInterventionAuditConfig = {type: 'customBlocker',policy: 'always',- resolver: (toolArgs) => toolArgs.dangerous === true,+ resolver: async (toolArgs) => toolArgs.dangerous === true,};const agent = new GeneralChatAgent({@@ -2118,7 +2180,7 @@ describe('GeneralChatAgent', () => {const customResolver: GlobalInterventionAuditConfig = {type: 'customBlocker',policy: 'always',- resolver: (toolArgs) => toolArgs.blocked === true,+ resolver: async (toolArgs) => toolArgs.blocked === true,};const agent = new GeneralChatAgent({@@ -2159,7 +2221,7 @@ describe('GeneralChatAgent', () => {const customResolver: GlobalInterventionAuditConfig = {type: 'softBlocker',policy: 'required',- resolver: () => true, // always triggers+ resolver: async () => true, // always triggers};const agent = new GeneralChatAgent({@@ -2205,7 +2267,7 @@ describe('GeneralChatAgent', () => {const customResolver: GlobalInterventionAuditConfig = {type: 'softBlocker',policy: 'required',- resolver: () => true,+ resolver: async () => true,};const agent = new GeneralChatAgent({@@ -2252,7 +2314,7 @@ describe('GeneralChatAgent', () => {const spyResolver: GlobalInterventionAuditConfig = {type: 'spy',policy: 'always',- resolver: (_toolArgs, metadata) => {+ resolver: async (_toolArgs, metadata) => {capturedMetadata = metadata;return false;},@@ -2302,7 +2364,7 @@ describe('GeneralChatAgent', () => {const resolver1: GlobalInterventionAuditConfig = {type: 'first',policy: 'always',- resolver: () => {+ resolver: async () => {callOrder.push('first');return true; // matches},@@ -2311,7 +2373,7 @@ describe('GeneralChatAgent', () => {const resolver2: GlobalInterventionAuditConfig = {type: 'second',policy: 'required',- resolver: () => {+ resolver: async () => {callOrder.push('second');return true;},diff --git a/packages/agent-runtime/src/audit/__tests__/createSecurityBlacklistAudit.test.ts b/packages/agent-runtime/src/audit/__tests__/createSecurityBlacklistAudit.test.tsindex a733362611c..0f3346a59e7 100644--- a/packages/agent-runtime/src/audit/__tests__/createSecurityBlacklistAudit.test.ts+++ b/packages/agent-runtime/src/audit/__tests__/createSecurityBlacklistAudit.test.ts@@ -8,18 +8,17 @@ import {describe('createSecurityBlacklistAudit', () => {describe('createSecurityBlacklistAudit', () => {- it('should return true for blacklisted commands using default blacklist', () => {+ it('should return true for blacklisted commands using default blacklist', async () => {const audit = createSecurityBlacklistAudit();- // "rm -rf /" matches the default blacklist- expect(audit({ command: 'rm -rf /' })).toBe(true);+ await expect(audit({ command: 'rm -rf /' })).resolves.toBe(true);});- it('should return false for safe commands using default blacklist', () => {+ it('should return false for safe commands using default blacklist', async () => {const audit = createSecurityBlacklistAudit();- expect(audit({ command: 'ls -la' })).toBe(false);+ await expect(audit({ command: 'ls -la' })).resolves.toBe(false);});- it('should use blacklist from metadata when provided', () => {+ it('should use blacklist from metadata when provided', async () => {const audit = createSecurityBlacklistAudit();const customBlacklist = [{@@ -28,39 +27,39 @@ describe('createSecurityBlacklistAudit', () => {},];- expect(+ await 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);+ ).resolves.toBe(true);+ await expect(+ audit({ command: 'rm -rf /' }, { securityBlacklist: customBlacklist }),+ ).resolves.toBe(false);});- it('should fall back to DEFAULT_SECURITY_BLACKLIST when metadata has no blacklist', () => {+ it('should fall back to DEFAULT_SECURITY_BLACKLIST when metadata has no blacklist', async () => {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);+ await expect(audit({ command: 'rm -rf /' }, {})).resolves.toBe(true);+ await expect(audit({ command: 'rm -rf /' }, { otherField: 'value' })).resolves.toBe(true);});- it('should fall back to DEFAULT_SECURITY_BLACKLIST when metadata is undefined', () => {+ it('should fall back to DEFAULT_SECURITY_BLACKLIST when metadata is undefined', async () => {const audit = createSecurityBlacklistAudit();- expect(audit({ command: 'rm -rf /' }, undefined)).toBe(true);+ await expect(audit({ command: 'rm -rf /' }, undefined)).resolves.toBe(true);});- it('should return false for empty tool args', () => {+ it('should return false for empty tool args', async () => {const audit = createSecurityBlacklistAudit();- expect(audit({})).toBe(false);+ await expect(audit({})).resolves.toBe(false);});- it('should detect sensitive file paths via default blacklist', () => {+ it('should detect sensitive file paths via default blacklist', async () => {const audit = createSecurityBlacklistAudit();- expect(audit({ path: '/home/user/.env' })).toBe(true);- expect(audit({ path: '/home/user/.ssh/id_rsa' })).toBe(true);+ await expect(audit({ path: '/home/user/.env' })).resolves.toBe(true);+ await expect(audit({ path: '/home/user/.ssh/id_rsa' })).resolves.toBe(true);});- it('should return false when metadata provides empty blacklist', () => {+ it('should return false when metadata provides empty blacklist', async () => {const audit = createSecurityBlacklistAudit();- expect(audit({ command: 'rm -rf /' }, { securityBlacklist: [] })).toBe(false);+ await expect(audit({ command: 'rm -rf /' }, { securityBlacklist: [] })).resolves.toBe(false);});});@@ -73,11 +72,11 @@ describe('createSecurityBlacklistAudit', () => {expect(typeof config.resolver).toBe('function');});- it('should have a working resolver that blocks blacklisted commands', () => {+ it('should have a working resolver that blocks blacklisted commands', async () => {const config = createSecurityBlacklistGlobalAudit();- expect(config.resolver({ command: 'rm -rf /' })).toBe(true);- expect(config.resolver({ command: 'ls -la' })).toBe(false);+ await expect(config.resolver({ command: 'rm -rf /' })).resolves.toBe(true);+ await expect(config.resolver({ command: 'ls -la' })).resolves.toBe(false);});});diff --git a/packages/agent-runtime/src/audit/createSecurityBlacklistAudit.ts b/packages/agent-runtime/src/audit/createSecurityBlacklistAudit.tsindex f94e95e4b90..a06de5d131b 100644--- a/packages/agent-runtime/src/audit/createSecurityBlacklistAudit.ts+++ b/packages/agent-runtime/src/audit/createSecurityBlacklistAudit.ts@@ -13,7 +13,7 @@ export const SECURITY_BLACKLIST_AUDIT_TYPE = 'securityBlacklist';* 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 => {+ return async (toolArgs: Record<string, any>, metadata?: Record<string, any>) => {const securityBlacklist = metadata?.securityBlacklist ?? DEFAULT_SECURITY_BLACKLIST;const result = InterventionChecker.checkSecurityBlacklist(securityBlacklist, toolArgs);return result.blocked;diff --git a/packages/builtin-tool-local-system/src/__tests__/interventionAudit.test.ts b/packages/builtin-tool-local-system/src/__tests__/interventionAudit.test.tsindex c86bac1cbda..f341c07e231 100644--- a/packages/builtin-tool-local-system/src/__tests__/interventionAudit.test.ts+++ b/packages/builtin-tool-local-system/src/__tests__/interventionAudit.test.ts@@ -1,105 +1,115 @@import { describe, expect, it } from 'vitest';-import { pathScopeAudit } from '../interventionAudit';+import { createPathScopeAudit, 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 no working directory in metadata', async () => {+ await expect(pathScopeAudit({ path: '/anywhere' })).resolves.toBe(false);+ await expect(pathScopeAudit({ path: '/anywhere' }, {})).resolves.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 path is within working directory', async () => {+ await expect(+ pathScopeAudit({ path: '/Users/me/project/src/index.ts' }, metadata),+ ).resolves.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 path resolves within working directory', async () => {+ await expect(pathScopeAudit({ path: 'src/index.ts' }, metadata)).resolves.toBe(false);});- it('should return false when relative directory resolves within working directory', () => {- expect(pathScopeAudit({ directory: 'src' }, metadata)).toBe(false);+ it('should return false when relative directory resolves within working directory', async () => {+ await expect(pathScopeAudit({ directory: 'src' }, metadata)).resolves.toBe(false);});- it('should resolve relative paths against tool scope when provided', () => {- expect(+ it('should resolve relative paths against tool scope when provided', async () => {+ await expect(pathScopeAudit({ scope: 'packages', path: 'a.ts' },{ workingDirectory: '/Users/me/project' },),- ).toBe(false);+ ).resolves.toBe(false);});- it('should return false when path equals working directory', () => {- expect(pathScopeAudit({ path: '/Users/me/project' }, metadata)).toBe(false);+ it('should return false when path equals working directory', async () => {+ await expect(pathScopeAudit({ path: '/Users/me/project' }, metadata)).resolves.toBe(false);});- it('should return false for empty tool args', () => {- expect(pathScopeAudit({}, metadata)).toBe(false);+ it('should return false for empty tool args', async () => {+ await expect(pathScopeAudit({}, metadata)).resolves.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 path is outside working directory', async () => {+ await expect(+ pathScopeAudit({ path: '/Users/me/other-project/file.ts' }, metadata),+ ).resolves.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 allow /tmp paths (system temp directory)', () => {- expect(pathScopeAudit({ file_path: '/tmp/secret.txt' }, metadata)).toBe(false);+ it('should return true when relative path traversal escapes working directory', async () => {+ await expect(pathScopeAudit({ path: '../other-project/file.ts' }, metadata)).resolves.toBe(+ true,+ );});- it('should return true when file_path is outside working directory', () => {- expect(pathScopeAudit({ file_path: '/var/data/secret.txt' }, metadata)).toBe(true);+ it('should return true when file_path is outside working directory', async () => {+ await expect(pathScopeAudit({ file_path: '/home/other/secret.txt' }, metadata)).resolves.toBe(+ true,+ );});- it('should return true when directory is outside working directory', () => {- expect(pathScopeAudit({ directory: '/etc' }, metadata)).toBe(true);+ it('should return true when directory is outside working directory', async () => {+ await expect(pathScopeAudit({ directory: '/etc' }, metadata)).resolves.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 scope is outside working directory', async () => {+ await expect(pathScopeAudit({ scope: '/Users/me/other-project' }, metadata)).resolves.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 true when pattern is an absolute glob outside working directory', async () => {+ await expect(pathScopeAudit({ pattern: '/Users/me/other/**/*.ts' }, metadata)).resolves.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 return false when pattern is within working directory', async () => {+ await expect(+ pathScopeAudit({ pattern: '/Users/me/project/src/**/*.ts' }, metadata),+ ).resolves.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 relative glob patterns (not a path)', async () => {+ await expect(pathScopeAudit({ pattern: '**/*.ts' }, metadata)).resolves.toBe(false);+ await expect(pathScopeAudit({ pattern: 'src/**/*.tsx' }, metadata)).resolves.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 ignore regex patterns from grepContent', async () => {+ await expect(pathScopeAudit({ pattern: 'TODO|FIXME' }, metadata)).resolves.toBe(false);+ await expect(pathScopeAudit({ pattern: 'function\\s+\\w+' }, metadata)).resolves.toBe(false);+ await expect(pathScopeAudit({ pattern: '^import .* from' }, metadata)).resolves.toBe(false);});- it('should return true when any path in items is outside working directory', () => {- expect(+ it('should return true when any path in items is outside working directory', async () => {+ await expect(pathScopeAudit({items: [{ oldPath: '/Users/me/project/a.ts', newPath: '/Users/me/other/b.ts' }],},metadata,),- ).toBe(true);+ ).resolves.toBe(true);});});describe('items array handling', () => {- it('should return false when all items paths are within working directory', () => {- expect(+ it('should return false when all items paths are within working directory', async () => {+ await expect(pathScopeAudit({items: [@@ -109,44 +119,91 @@ describe('pathScopeAudit', () => {},metadata,),- ).toBe(false);+ ).resolves.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 oldPath', async () => {+ await expect(+ pathScopeAudit({ items: [{ oldPath: '/outside/path.ts' }] }, metadata),+ ).resolves.toBe(true);});- it('should handle items with only newPath', () => {- expect(pathScopeAudit({ items: [{ newPath: '/outside/path.ts' }] }, metadata)).toBe(true);+ it('should handle items with only newPath', async () => {+ await expect(+ pathScopeAudit({ items: [{ newPath: '/outside/path.ts' }] }, metadata),+ ).resolves.toBe(true);});});describe('mixed parameters', () => {- it('should return true if any parameter is outside, even if others are inside', () => {- expect(+ it('should return true if any parameter is outside, even if others are inside', async () => {+ await expect(pathScopeAudit({ path: '/Users/me/project/file.ts', scope: '/Users/me/other' }, metadata),- ).toBe(true);+ ).resolves.toBe(true);});- it('should return false when all parameters are within working directory', () => {- expect(+ it('should return false when all parameters are within working directory', async () => {+ await expect(pathScopeAudit({ path: '/Users/me/project/src/file.ts', scope: '/Users/me/project' },metadata,),- ).toBe(false);+ ).resolves.toBe(false);+ });+ });++ describe('safe path exclusions', () => {+ it('should require intervention for safe-path candidates when no resolver is configured', async () => {+ await expect(pathScopeAudit({ path: '/tmp/test-file.ts' }, metadata)).resolves.toBe(true);+ await expect(pathScopeAudit({ file_path: '/tmp/secret.txt' }, metadata)).resolves.toBe(true);+ await expect(pathScopeAudit({ directory: '/tmp' }, metadata)).resolves.toBe(true);+ await expect(pathScopeAudit({ path: '/tmp/subdir/file.ts' }, metadata)).resolves.toBe(true);+ });++ it('should skip intervention when an injected resolver confirms all safe paths', async () => {+ const safePathAudit = createPathScopeAudit({+ areAllPathsSafe: async () => true,+ });++ await expect(safePathAudit({ path: '/tmp/test-file.ts' }, metadata)).resolves.toBe(false);+ await expect(safePathAudit({ path: '/var/tmp/output.log' }, metadata)).resolves.toBe(false);+ await expect(+ safePathAudit(+ {+ items: [{ oldPath: '/tmp/a.ts', newPath: '/tmp/b.ts' }],+ },+ metadata,+ ),+ ).resolves.toBe(false);+ });++ it('should still require intervention when mixing safe and unsafe paths', async () => {+ const safePathAudit = createPathScopeAudit({+ areAllPathsSafe: async () => true,+ });++ await expect(+ safePathAudit(+ {+ items: [{ oldPath: '/tmp/a.ts', newPath: '/Users/me/other/b.ts' }],+ },+ metadata,+ ),+ ).resolves.toBe(true);});});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 catch path traversal that escapes working directory', async () => {+ await expect(+ pathScopeAudit({ path: '/Users/me/project/../other/file.ts' }, metadata),+ ).resolves.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,- );+ it('should allow path traversal that stays within working directory', async () => {+ await expect(+ pathScopeAudit({ path: '/Users/me/project/src/../lib/file.ts' }, metadata),+ ).resolves.toBe(false);});});});diff --git a/packages/builtin-tool-local-system/src/index.ts b/packages/builtin-tool-local-system/src/index.tsindex fe954161488..ca7dd4e4555 100644--- a/packages/builtin-tool-local-system/src/index.ts+++ b/packages/builtin-tool-local-system/src/index.ts@@ -1,4 +1,4 @@-export { pathScopeAudit } from './interventionAudit';+export { createPathScopeAudit, 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.tsindex ced4a7f21e2..d1467976f10 100644--- a/packages/builtin-tool-local-system/src/interventionAudit.ts+++ b/packages/builtin-tool-local-system/src/interventionAudit.ts@@ -1,11 +1,36 @@import { type DynamicInterventionResolver } from '@lobechat/types';-import { isPathWithinScope, resolvePathWithScope } from './utils/path';+import { normalizePathForScope, resolvePathWithScope } from './utils/path';++const SAFE_PATH_PREFIXES = ['/tmp', '/var/tmp'] as const;++interface SafePathAuditParams {+ paths: string[];+ resolveAgainstScope: string;+}++interface PathScopeAuditOptions {+ areAllPathsSafe?: (params: SafePathAuditParams) => boolean | Promise<boolean>;+}++const isWithinPathPrefixes = (targetPath: string, prefixes: readonly string[]): boolean =>+ prefixes.some((prefix) => targetPath === prefix || targetPath.startsWith(prefix + '/'));++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'];@@ -17,13 +42,10 @@ const extractPaths = (toolArgs: Record<string, any>): string[] => {}}- // 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') {@@ -36,33 +58,51 @@ const extractPaths = (toolArgs: Record<string, any>): string[] => {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;+const areAllPathsSafeCandidates = (paths: string[], resolveAgainstScope: string): boolean => {+ if (paths.length === 0) return false;- // If no working directory is set, no intervention needed- if (!workingDirectory) {- return false;- }+ return paths.every((currentPath) => {+ const resolvedPath = resolvePathWithScope(currentPath, resolveAgainstScope) ?? currentPath;+ const normalizedPath = normalizePathForScope(resolvedPath);- // Match runtime behavior: a tool-provided scope is interpreted relative to workingDirectory.- // If the resolved scope escapes the workingDirectory, intervention is required.- if (toolScope && !isPathWithinScope(toolScope, workingDirectory, workingDirectory)) {- return true;- }+ return isWithinPathPrefixes(normalizedPath, SAFE_PATH_PREFIXES);+ });+};++export const createPathScopeAudit = (+ options: PathScopeAuditOptions = {},+): DynamicInterventionResolver => {+ const { areAllPathsSafe } = options;++ return async (+ toolArgs: Record<string, any>,+ metadata?: Record<string, any>,+ ): Promise<boolean> => {+ const workingDirectory = metadata?.workingDirectory as string | undefined;+ const toolScope = toolArgs.scope as string | undefined;++ if (!workingDirectory) {+ return false;+ }- const effectiveScope =- resolvePathWithScope(toolScope, workingDirectory) ?? toolScope ?? workingDirectory;+ if (toolScope && !isPathWithinWorkingDirectory(toolScope, workingDirectory, workingDirectory)) {+ return true;+ }++ const effectiveScope =+ resolvePathWithScope(toolScope, workingDirectory) ?? toolScope ?? workingDirectory;- const paths = extractPaths(toolArgs);+ const paths = extractPaths(toolArgs);- // Return true if any path is outside the working directory- return paths.some((path) => !isPathWithinScope(path, workingDirectory, effectiveScope));+ if (areAllPathsSafe && areAllPathsSafeCandidates(paths, effectiveScope)) {+ const allSafe = await areAllPathsSafe({ paths, resolveAgainstScope: effectiveScope });+ if (allSafe) return false;+ }++ return paths.some(+ (currentPath) => !isPathWithinWorkingDirectory(currentPath, workingDirectory, effectiveScope),+ );+ };};++export const pathScopeAudit = createPathScopeAudit();diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.tsindex 5d042643fdd..49a2740b62d 100644--- a/packages/electron-client-ipc/src/types/localSystem.ts+++ b/packages/electron-client-ipc/src/types/localSystem.ts@@ -102,6 +102,15 @@ export interface WriteLocalFileParams {path: string;}+export interface AuditSafePathsParams {+ paths: string[];+ resolveAgainstScope: string;+}++export interface AuditSafePathsResult {+ allSafe: boolean;+}+export interface LocalReadFileResult {/*** Character count of the content within the specified `loc` range.diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.tsindex 497f523ca7d..0ca8530f9ff 100644--- a/packages/types/src/tool/builtin.ts+++ b/packages/types/src/tool/builtin.ts@@ -61,7 +61,7 @@ export const RenderDisplayControlSchema = z.enum(['collapsed', 'expand', 'alwaysexport type DynamicInterventionResolver = (toolArgs: Record<string, any>,metadata?: Record<string, any>,-) => boolean;+) => Promise<boolean>;/*** Global intervention audit configurationdiff --git a/src/services/electron/localFileService.ts b/src/services/electron/localFileService.tsindex 085cfaa016a..3e8f336ad29 100644--- a/src/services/electron/localFileService.ts+++ b/src/services/electron/localFileService.ts@@ -1,4 +1,6 @@import {+ type AuditSafePathsParams,+ type AuditSafePathsResult,type EditLocalFileParams,type EditLocalFileResult,type GetCommandOutputParams,@@ -72,6 +74,10 @@ class LocalFileService {return ensureElectronIpc().localSystem.handleWriteFile(params);}+ async auditSafePaths(params: AuditSafePathsParams): Promise<AuditSafePathsResult> {+ return ensureElectronIpc().localSystem.auditSafePaths(params);+ }+async prepareSkillDirectory(params: PrepareSkillDirectoryParams,): Promise<PrepareSkillDirectoryResult> {diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.tsindex c8c27c49ae9..eed9334339e 100644--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts@@ -6,9 +6,9 @@ import {type Usage,} from '@lobechat/agent-runtime';import { AgentRuntime, computeStepContext, GeneralChatAgent } from '@lobechat/agent-runtime';+import { createPathScopeAudit } from '@lobechat/builtin-tool-local-system';import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';import { manualModeExcludeToolIds } from '@lobechat/builtin-tools';-import { dynamicInterventionAudits } from '@lobechat/builtin-tools/dynamicInterventionAudits';import { isDesktop } from '@lobechat/const';import { type ToolsEngine } from '@lobechat/context-engine';import {@@ -22,6 +22,7 @@ import { t } from 'i18next';import { createAgentToolsEngine } from '@/helpers/toolEngineering';import { type ResolvedAgentConfig } from '@/services/chat/mecha';import { resolveAgentConfig } from '@/services/chat/mecha';+import { localFileService } from '@/services/electron/localFileService';import { messageService } from '@/services/message';import { getAgentStoreState } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';@@ -44,6 +45,17 @@ import {const log = debug('lobe-store:streaming-executor');+const dynamicInterventionAudits = {+ pathScopeAudit: createPathScopeAudit({+ areAllPathsSafe: async ({ paths, resolveAgainstScope }) => {+ if (!isDesktop) return false;++ const result = await localFileService.auditSafePaths({ paths, resolveAgainstScope });+ return result.allSafe;+ },+ }),+};+const hasReferTopicNode = (editorData: Record<string, any> | null | undefined): boolean => {if (!editorData) return false;const walk = (node: any): boolean => {