π€― 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
π fix: bypass audits for headless tool calls (#15406)
Rylan Caicd171d351031
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex b4fd5b00fab..772a75b2792 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -158,6 +158,7 @@ export class GeneralChatAgent implements Agent {let globalBlocked = false;let globalPolicy: HumanInterventionPolicy = 'always';+ // Default global audits are ordered so always-block rules match firstfor (const globalResolver of globalResolvers) {if (await globalResolver.resolver(toolArgs, resolverMetadata)) {globalBlocked = true;@@ -166,17 +167,6 @@ export class GeneralChatAgent implements Agent {}}- // Phase 2: Headless mode - fully automated for async tasks- if (approvalMode === 'headless') {- if (globalBlocked && globalPolicy === 'always') {- // Skip 'always' blocked tools entirely (don't execute, don't wait for approval)- continue;- }- // All other tools execute directly (including overridable global blocks)- toolsToExecute.push(toolCalling);- continue;- }-// For non-headless modes: 'always' global block requires intervention unconditionallyif (globalBlocked && globalPolicy === 'always') {toolsNeedingIntervention.push(toolCalling);@@ -203,6 +193,12 @@ export class GeneralChatAgent implements Agent {continue;}+ // Phase 3.5: Headless mode auto-runs global blocks with non-always policy+ if (approvalMode === 'headless' && globalBlocked && globalPolicy !== 'always') {+ toolsToExecute.push(toolCalling);+ continue;+ }+// Phase 3.5: Handle overridable global block (policy !== 'always')if (globalBlocked && globalPolicy !== 'always') {toolsNeedingIntervention.push(toolCalling);@@ -515,13 +511,23 @@ export class GeneralChatAgent implements Agent {}// Request approval for tools that need intervention- // Runtime will execute this after safe tools and pause with status='waiting_for_human'+ // Non-headless mode waits for human approval; headless mode returns blocked tool results.if (toolsNeedingIntervention.length > 0) {- instructions.push({- pendingToolsCalling: toolsNeedingIntervention,- reason: 'human_intervention_required',- type: 'request_human_approve',- });+ if (state.userInterventionConfig?.approvalMode === 'headless') {+ instructions.push({+ payload: {+ parentMessageId,+ toolsCalling: toolsNeedingIntervention,+ },+ type: 'resolve_blocked_tools',+ } satisfies AgentInstruction);+ } else {+ instructions.push({+ pendingToolsCalling: toolsNeedingIntervention,+ reason: 'human_intervention_required',+ type: 'request_human_approve',+ });+ }}return instructions;diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.tsindex a462525b2c3..2a510829724 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -2625,7 +2625,7 @@ describe('GeneralChatAgent', () => {]);});- it('should skip tool in headless mode when global resolver with policy always triggers', async () => {+ it('should resolve blocked tool in headless mode when global resolver with policy always triggers', async () => {const customResolver: GlobalInterventionAuditConfig = {type: 'customBlocker',policy: 'always',@@ -2662,8 +2662,16 @@ describe('GeneralChatAgent', () => {const result = await agent.runner(context, state);- // Tool is skipped entirely in headless mode with 'always' policy- expect(result).toEqual([]);+ // Headless/CLI has no human intervention UI, so return a blocked tool result for replan.+ expect(result).toEqual([+ {+ payload: {+ parentMessageId: 'msg-1',+ toolsCalling: [blockedTool],+ },+ type: 'resolve_blocked_tools',+ },+ ]);});it('should execute tool in headless mode when global resolver with policy required triggers', async () => {@@ -2898,10 +2906,49 @@ describe('GeneralChatAgent', () => {},]);});++ it('should still require intervention for default always blacklist tools in auto-run mode', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });++ const alwaysTool: ChatToolPayload = {+ id: 'call-1',+ identifier: 'bash',+ apiName: 'bash',+ arguments: '{"command":"rm -rf /"}',+ type: 'builtin',+ };++ const state = createMockState({+ toolManifestMap: {+ bash: { identifier: 'bash', humanIntervention: 'never' },+ },+ userInterventionConfig: { approvalMode: 'auto-run' },+ });++ const context = createMockContext('llm_result', {+ hasToolsCalling: true,+ toolsCalling: [alwaysTool],+ parentMessageId: 'msg-1',+ });++ const result = await agent.runner(context, state);++ expect(result).toEqual([+ {+ type: 'request_human_approve',+ pendingToolsCalling: [alwaysTool],+ reason: 'human_intervention_required',+ },+ ]);+ });});describe('headless mode (for async tasks)', () => {- it('should execute all tools directly in headless mode including those requiring approval', async () => {+ it('should resolve tool-level required tools in headless mode', async () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },operationId: 'test-session',@@ -2936,19 +2983,19 @@ describe('GeneralChatAgent', () => {const result = await agent.runner(context, state);- // Should execute directly in headless mode+ // Headless/CLI cannot request tool-level approval, so return a blocked tool result for replan.expect(result).toEqual([{- type: 'call_tool',payload: {parentMessageId: 'msg-1',- toolCalling: toolCall,+ toolsCalling: [toolCall],},+ type: 'resolve_blocked_tools',},]);});- it('should execute tools with "always" policy in headless mode', async () => {+ it('should resolve tools with "always" policy in headless mode', async () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },operationId: 'test-session',@@ -2988,19 +3035,19 @@ describe('GeneralChatAgent', () => {const result = await agent.runner(context, state);- // Should execute directly in headless mode, even for 'always' policy+ // Headless/CLI cannot ask a human to approve always-policy tools, so return results for replan.expect(result).toEqual([{- type: 'call_tool',payload: {parentMessageId: 'msg-1',- toolCalling: alwaysTool,+ toolsCalling: [alwaysTool],},+ type: 'resolve_blocked_tools',},]);});- it('should skip security blacklisted tools in headless mode', async () => {+ it('should resolve security blacklisted tools in headless mode', async () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },operationId: 'test-session',@@ -3036,18 +3083,26 @@ describe('GeneralChatAgent', () => {const result = await agent.runner(context, state);- // Should return empty array (tool is skipped, not executed or pending)- expect(result).toEqual([]);+ // Headless/CLI cannot wait on security blacklist approval, so return a blocked result for replan.+ expect(result).toEqual([+ {+ payload: {+ parentMessageId: 'msg-1',+ toolsCalling: [blacklistedTool],+ },+ type: 'resolve_blocked_tools',+ },+ ]);});- it('should handle mixed tools in headless mode - execute safe ones, skip blacklisted', async () => {+ it('should resolve all tools needing approval in headless mode', async () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },operationId: 'test-session',modelRuntimeConfig: mockModelRuntimeConfig,});- const safeTool: ChatToolPayload = {+ const requiredTool: ChatToolPayload = {id: 'call-1',identifier: 'web-search',apiName: 'search',@@ -3097,25 +3152,25 @@ describe('GeneralChatAgent', () => {const context = createMockContext('llm_result', {hasToolsCalling: true,- toolsCalling: [safeTool, blacklistedTool, alwaysTool],+ toolsCalling: [requiredTool, blacklistedTool, alwaysTool],parentMessageId: 'msg-1',});const result = await agent.runner(context, state);- // Should execute safeTool and alwaysTool, skip blacklistedTool+ // Headless/CLI batches all tools that need intervention into blocked results for replan.expect(result).toEqual([{- type: 'call_tools_batch',payload: {parentMessageId: 'msg-1',- toolsCalling: [safeTool, alwaysTool],+ toolsCalling: [requiredTool, blacklistedTool, alwaysTool],},+ type: 'resolve_blocked_tools',},]);});- it('should execute multiple tools as batch in headless mode', async () => {+ it('should resolve multiple tools requiring approval in headless mode', async () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },operationId: 'test-session',@@ -3156,14 +3211,14 @@ describe('GeneralChatAgent', () => {const result = await agent.runner(context, state);- // Should execute both tools as batch in headless mode+ // Headless/CLI returns blocked results for every tool that would otherwise need approval.expect(result).toEqual([{- type: 'call_tools_batch',payload: {parentMessageId: 'msg-1',toolsCalling: [tool1, tool2],},+ type: 'resolve_blocked_tools',},]);});diff --git a/packages/agent-runtime/src/audit/__tests__/createSecurityBlacklistAudit.test.ts b/packages/agent-runtime/src/audit/__tests__/createSecurityBlacklistAudit.test.tsindex 0f3346a59e7..051c7ec36cc 100644--- a/packages/agent-runtime/src/audit/__tests__/createSecurityBlacklistAudit.test.ts+++ b/packages/agent-runtime/src/audit/__tests__/createSecurityBlacklistAudit.test.ts@@ -35,6 +35,21 @@ describe('createSecurityBlacklistAudit', () => {).resolves.toBe(false);});+ it('should respect rule policy when using metadata blacklist', async () => {+ const audit = createSecurityBlacklistAudit('required');+ const customBlacklist = [+ {+ description: 'Block custom command',+ match: { command: { pattern: 'custom-danger.*', type: 'regex' as const } },+ policy: 'required' as const,+ },+ ];++ await expect(+ audit({ command: 'custom-danger --force' }, { securityBlacklist: customBlacklist }),+ ).resolves.toBe(true);+ });+it('should fall back to DEFAULT_SECURITY_BLACKLIST when metadata has no blacklist', async () => {const audit = createSecurityBlacklistAudit();await expect(audit({ command: 'rm -rf /' }, {})).resolves.toBe(true);@@ -51,8 +66,8 @@ describe('createSecurityBlacklistAudit', () => {await expect(audit({})).resolves.toBe(false);});- it('should detect sensitive file paths via default blacklist', async () => {- const audit = createSecurityBlacklistAudit();+ it('should detect sensitive file paths via required blacklist rules', async () => {+ const audit = createSecurityBlacklistAudit('required');await expect(audit({ path: '/home/user/.env' })).resolves.toBe(true);await expect(audit({ path: '/home/user/.ssh/id_rsa' })).resolves.toBe(true);});@@ -76,10 +91,29 @@ describe('createSecurityBlacklistAudit', () => {const config = createSecurityBlacklistGlobalAudit();await expect(config.resolver({ command: 'rm -rf /' })).resolves.toBe(true);+ await expect(config.resolver({ command: 'cat .env' })).resolves.toBe(false);await expect(config.resolver({ command: 'ls -la' })).resolves.toBe(false);});});+ describe('createSecurityBlacklistGlobalAudit(required)', () => {+ it('should return a required GlobalInterventionAuditConfig', () => {+ const config = createSecurityBlacklistGlobalAudit('required');++ expect(config.type).toBe(SECURITY_BLACKLIST_AUDIT_TYPE);+ expect(config.policy).toBe('required');+ expect(typeof config.resolver).toBe('function');+ });++ it('should block overridable sensitive commands only', async () => {+ const config = createSecurityBlacklistGlobalAudit('required');++ await expect(config.resolver({ command: 'cat .env' })).resolves.toBe(true);+ await expect(config.resolver({ command: 'cat /etc/ssh/sshd_config' })).resolves.toBe(true);+ await expect(config.resolver({ command: 'rm -rf /' })).resolves.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.tsindex a06de5d131b..dc23130f496 100644--- a/packages/agent-runtime/src/audit/createSecurityBlacklistAudit.ts+++ b/packages/agent-runtime/src/audit/createSecurityBlacklistAudit.ts@@ -1,6 +1,8 @@import {type DynamicInterventionResolver,type GlobalInterventionAuditConfig,+ type HumanInterventionPolicy,+ type SecurityBlacklistConfig,} from '@lobechat/types';import { InterventionChecker } from '../core/InterventionChecker';@@ -12,20 +14,27 @@ 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 => {+export const createSecurityBlacklistAudit = (+ policy: HumanInterventionPolicy = 'always',+): DynamicInterventionResolver => {return async (toolArgs: Record<string, any>, metadata?: Record<string, any>) => {- const securityBlacklist = metadata?.securityBlacklist ?? DEFAULT_SECURITY_BLACKLIST;- const result = InterventionChecker.checkSecurityBlacklist(securityBlacklist, toolArgs);+ const securityBlacklist: SecurityBlacklistConfig =+ metadata?.securityBlacklist ?? DEFAULT_SECURITY_BLACKLIST;+ const filteredBlacklist = securityBlacklist.filter(+ (rule) => (rule.policy ?? 'always') === policy,+ );+ const result = InterventionChecker.checkSecurityBlacklist(filteredBlacklist, 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(),+export const createSecurityBlacklistGlobalAudit = (+ policy: HumanInterventionPolicy = 'always',+): GlobalInterventionAuditConfig => ({+ policy,+ resolver: createSecurityBlacklistAudit(policy),type: SECURITY_BLACKLIST_AUDIT_TYPE,});diff --git a/packages/agent-runtime/src/audit/defaultSecurityBlacklist.ts b/packages/agent-runtime/src/audit/defaultSecurityBlacklist.tsindex e224a0fb032..d6d34c4b0ad 100644--- a/packages/agent-runtime/src/audit/defaultSecurityBlacklist.ts+++ b/packages/agent-runtime/src/audit/defaultSecurityBlacklist.ts@@ -2,10 +2,9 @@ import { type SecurityBlacklistConfig } from '@lobechat/types';/*** Default Security Blacklist- * These rules will ALWAYS block execution and require human intervention,- * regardless of user settings (even in auto-run mode)*- * This is the last line of defense against dangerous operations+ * These rules block execution and require human intervention by default.+ * Rules explicitly marked as 'required' can be bypassed by auto-run flows.** Note: `description` values are i18n keys (namespace: 'tool', prefix: 'securityBlacklist.')* and are translated in the intervention UI via `t(description)`.@@ -98,6 +97,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.sshConfig',@@ -107,6 +107,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},// ==================== Package Manager Dangers ====================@@ -118,6 +119,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},// ==================== Kernel & System Core Dangers ====================@@ -169,6 +171,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.envFiles',@@ -178,6 +181,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.sshPrivateKeys',@@ -188,6 +192,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.sshPrivateKeys',@@ -197,6 +202,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.awsCredentials',@@ -206,6 +212,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.awsCredentials',@@ -215,6 +222,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.dockerConfig',@@ -224,6 +232,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.dockerConfig',@@ -233,6 +242,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.kubeConfig',@@ -242,6 +252,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.kubeConfig',@@ -251,6 +262,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.gitCredentials',@@ -260,6 +272,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.gitCredentials',@@ -269,6 +282,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.npmrc',@@ -278,6 +292,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.npmrc',@@ -287,6 +302,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.historyFiles',@@ -297,6 +313,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.historyFiles',@@ -306,6 +323,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.browserCredentials',@@ -316,6 +334,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.gcpCredentials',@@ -325,6 +344,7 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},{description: 'securityBlacklist.gcpCredentials',@@ -334,5 +354,6 @@ export const DEFAULT_SECURITY_BLACKLIST: SecurityBlacklistConfig = [type: 'regex',},},+ policy: 'required',},];diff --git a/packages/agent-runtime/src/audit/globalAudit.ts b/packages/agent-runtime/src/audit/globalAudit.tsindex decb0b2a49c..916ca0db5eb 100644--- a/packages/agent-runtime/src/audit/globalAudit.ts+++ b/packages/agent-runtime/src/audit/globalAudit.ts@@ -4,4 +4,5 @@ import { createSecurityBlacklistGlobalAudit } from './createSecurityBlacklistAudexport const createDefaultGlobalAudits = (): GlobalInterventionAuditConfig[] => [createSecurityBlacklistGlobalAudit(),+ createSecurityBlacklistGlobalAudit('required'),];diff --git a/packages/agent-runtime/src/core/__tests__/runtime.test.ts b/packages/agent-runtime/src/core/__tests__/runtime.test.tsindex df1ca68795a..50f10e92702 100644--- a/packages/agent-runtime/src/core/__tests__/runtime.test.ts+++ b/packages/agent-runtime/src/core/__tests__/runtime.test.ts@@ -1172,6 +1172,57 @@ describe('AgentRuntime', () => {expect(result.nextContext?.payload).toHaveProperty('toolCount', 3);});+ it('should resolve blocked tools and continue without waiting for human approval', async () => {+ class BlockedToolAgent implements Agent {+ async runner(context: AgentRuntimeContext, _state: AgentState) {+ if (context.phase === 'user_input') {+ return {+ payload: {+ parentMessageId: 'assistant-1',+ toolsCalling: [+ {+ apiName: 'bash',+ arguments: '{"command":"rm -rf /"}',+ id: 'call_blocked',+ identifier: 'bash',+ type: 'builtin' as const,+ },+ ],+ },+ type: 'resolve_blocked_tools' as const,+ };+ }++ return { reason: 'completed' as const, type: 'finish' as const };+ }+ }++ const runtime = new AgentRuntime(new BlockedToolAgent());+ const state = AgentRuntime.createInitialState({+ messages: [{ content: 'Try a blocked tool', role: 'user' }],+ operationId: 'blocked-tool-test',+ });++ const result = await runtime.step(state);++ expect(result.newState.status).toBe('running');+ expect(result.events).toEqual([+ {+ id: 'call_blocked',+ result: {+ content: 'Blocked by security/privacy.',+ success: false,+ },+ type: 'tool_result',+ },+ ]);+ expect(result.nextContext?.phase).toBe('tools_batch_result');+ expect(result.nextContext?.payload).toMatchObject({+ parentMessageId: 'assistant-1',+ toolCount: 1,+ });+ });+// Regression test for Gemini 3 thoughtSignature must survive the// OpenAI ToolsCalling -> ChatToolPayload normalization in call_tools_batch,// otherwise Gemini 3 400s on the second tool_call turn.diff --git a/packages/agent-runtime/src/core/runtime.ts b/packages/agent-runtime/src/core/runtime.tsindex c4e168c0026..c700f561634 100644--- a/packages/agent-runtime/src/core/runtime.ts+++ b/packages/agent-runtime/src/core/runtime.ts@@ -7,6 +7,7 @@ import type {AgentInstruction,AgentInstructionCallTool,AgentInstructionCallToolsBatch,+ AgentInstructionResolveBlockedTools,AgentRuntimeContext,AgentState,Cost,@@ -42,6 +43,7 @@ export class AgentRuntime {request_human_approve: this.createHumanApproveExecutor(),request_human_prompt: this.createHumanPromptExecutor(),request_human_select: this.createHumanSelectExecutor(),+ resolve_blocked_tools: this.createResolveBlockedToolsExecutor(),// Config executors override built-in...config.executors,// Agent provided executors have highest priority@@ -571,6 +573,46 @@ export class AgentRuntime {};}+ /** Create blocked tools executor */+ private createResolveBlockedToolsExecutor(): InstructionExecutor {+ return async (instruction, state) => {+ const { payload } = instruction as AgentInstructionResolveBlockedTools;+ const newState = structuredClone(state);+ const events: AgentEvent[] = [];++ for (const toolCalling of payload.toolsCalling) {+ const result = {+ content: 'Blocked by security/privacy.',+ success: false,+ };++ newState.messages.push({+ content: result.content,+ role: 'tool',+ tool_call_id: toolCalling.id,+ });+ events.push({ id: toolCalling.id, result, type: 'tool_result' });+ }++ newState.lastModified = new Date().toISOString();+ newState.status = 'running';++ return {+ events,+ newState,+ nextContext: {+ operationId: this.operationId,+ payload: {+ parentMessageId: payload.parentMessageId,+ toolCount: payload.toolsCalling.length,+ },+ phase: 'tools_batch_result',+ session: this.createSessionContext(newState),+ },+ };+ };+ }+/** Create human approve executor */private createHumanApproveExecutor(): InstructionExecutor {return async (instruction, state) => {diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.tsindex 8f99183b3e7..d92b8ace7c7 100644--- a/packages/agent-runtime/src/types/instruction.ts+++ b/packages/agent-runtime/src/types/instruction.ts@@ -273,6 +273,16 @@ export interface AgentInstructionResolveAbortedTools extends AgentInstructionBastype: 'resolve_aborted_tools';}+export interface AgentInstructionResolveBlockedTools extends AgentInstructionBase {+ payload: {+ /** Parent message ID (assistant message) */+ parentMessageId: string;+ /** Tool calls that were blocked and need tool results */+ toolsCalling: ChatToolPayload[];+ };+ type: 'resolve_blocked_tools';+}+// β Sub-Agent βββββββββββββββββββββββββββββββββββββββββββββexport interface AgentInstructionExecSubAgent extends AgentInstructionBase {@@ -373,6 +383,7 @@ export type AgentInstruction =| AgentInstructionCallTool| AgentInstructionCallToolsBatch| AgentInstructionResolveAbortedTools+ | AgentInstructionResolveBlockedTools// Sub-Agent| AgentInstructionExecSubAgent| AgentInstructionExecSubAgentsdiff --git a/packages/builtin-tool-local-system/src/systemRole.desktop.ts b/packages/builtin-tool-local-system/src/systemRole.desktop.tsindex 8565866a463..76576044647 100644--- a/packages/builtin-tool-local-system/src/systemRole.desktop.ts+++ b/packages/builtin-tool-local-system/src/systemRole.desktop.ts@@ -98,7 +98,8 @@ You have access to a set of tools to interact with the user's local file system:- For killing running terminal sessions: Use 'killCommand' with 'shell_id'.Treat terminal sessions as ongoing resources: when elapsed wait time and observed progress no longer match the command's expected lifecycle, reassess whether the session should continue running.- For remote device execution feedback: 'Device tool call failed (HTTP ...)' describes the remote-device/gateway layer, not necessarily the local operation.- - HTTP 403 or 503 can be transient during reconnects, restarts, or stale session replacement; retry can be reasonable.+ - HTTP 403 likely means an edge security policy blocked the request; replan with an equivalent approach or another tool such as runCommand.+ - HTTP 503 is usually transient; retry when the operation is safe to repeat.- HTTP 504 means the device did not respond within the wait window; the command may already have started, so retry only when the operation is safe to repeat.- For searching content in files: Use 'grepContent'. Provide:- 'pattern': The regex pattern to search for.diff --git a/packages/builtin-tool-local-system/src/systemRole.ts b/packages/builtin-tool-local-system/src/systemRole.tsindex 8edcef9f37d..34c25714595 100644--- a/packages/builtin-tool-local-system/src/systemRole.ts+++ b/packages/builtin-tool-local-system/src/systemRole.ts@@ -87,7 +87,8 @@ You have access to a set of tools to interact with the user's local file system:- For killing running terminal sessions: Use 'killCommand' with 'shell_id'.Treat terminal sessions as ongoing resources: when elapsed wait time and observed progress no longer match the command's expected lifecycle, reassess whether the session should continue running.- For remote device execution feedback: 'Device tool call failed (HTTP ...)' describes the remote-device/gateway layer, not necessarily the local operation.- - HTTP 403 or 503 can be transient during reconnects, restarts, or stale session replacement; retry can be reasonable.+ - HTTP 403 likely means an edge security policy blocked the request; replan with an equivalent approach or another tool such as runCommand.+ - HTTP 503 is usually transient; retry when the operation is safe to repeat.- HTTP 504 means the device did not respond within the wait window; the command may already have started, so retry only when the operation is safe to repeat.- For searching content in files: Use 'grepContent'. Provide:- 'pattern': The regex pattern to search for.diff --git a/packages/types/src/tool/intervention.ts b/packages/types/src/tool/intervention.tsindex c819de4494e..dc8dd2ebe49 100644--- a/packages/types/src/tool/intervention.ts+++ b/packages/types/src/tool/intervention.ts@@ -164,16 +164,24 @@ export interface SecurityBlacklistRule {* Same format as HumanInterventionRule.match*/match: Record<string, ArgumentMatcher>;++ /**+ * Policy to apply when this rule matches+ * @default 'always'+ */+ policy?: HumanInterventionPolicy;}export const SecurityBlacklistRuleSchema = z.object({description: z.string(),match: z.record(z.string(), ArgumentMatcherSchema),+ policy: HumanInterventionPolicySchema.optional(),});/*** Security Blacklist Configuration- * A list of rules that will always block execution and require intervention+ * A list of rules that block execution and require intervention.+ * Rules default to 'always' unless explicitly downgraded to 'required'.*/export type SecurityBlacklistConfig = SecurityBlacklistRule[];diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsindex 7934572ee77..c9954c184b2 100644--- a/src/server/modules/AgentRuntime/RuntimeExecutors.ts+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -3375,6 +3375,107 @@ export const createRuntimeExecutors = (};},+ /**+ * Resolve tools blocked in headless mode.+ * Creates tool results without executing the tools, then continues the loop.+ */+ resolve_blocked_tools: async (instruction, state) => {+ const { payload } = instruction as Extract<AgentInstruction, { type: 'resolve_blocked_tools' }>;+ const { parentMessageId, toolsCalling } = payload;+ const { operationId, stepIndex, streamManager } = ctx;+ const events: AgentEvent[] = [];+ const newState = structuredClone(state);+ const toolResults: Array<{ data: ToolExecutionResultResponse; toolCallId: string }> = [];+ const toolMessageIds: string[] = [];++ log('[%s:%d] Resolving %d blocked tools', operationId, stepIndex, toolsCalling.length);++ for (const toolPayload of toolsCalling) {+ const result: ToolExecutionResultResponse = {+ content: 'Blocked by security/privacy.',+ error: 'blocked_by_security_privacy',+ executionTime: 0,+ state: { type: 'blocked' },+ success: false,+ };++ await streamManager.publishStreamEvent(operationId, {+ data: {+ executionTime: 0,+ isSuccess: false,+ attempts: 0,+ maxAttempts: 0,+ payload: { parentMessageId, toolCalling: toolPayload },+ phase: 'tool_execution',+ result,+ },+ stepIndex,+ type: 'tool_end',+ });++ try {+ const toolMessage = await ctx.messageModel.create({+ agentId: state.metadata!.agentId!,+ content: result.content,+ metadata: { toolExecutionTimeMs: 0 },+ parentId: parentMessageId,+ plugin: toolPayload as any,+ pluginError: result.error,+ pluginIntervention: { rejectedReason: result.error, status: 'rejected' },+ pluginState: result.state,+ role: 'tool',+ threadId: state.metadata?.threadId,+ tool_call_id: toolPayload.id,+ topicId: state.metadata?.topicId,+ });+ toolMessageIds.push(toolMessage.id);+ } catch (error) {+ console.error('[resolve_blocked_tools] Failed to create blocked tool message: %O', error);+ const fatal = isMidOperationReferenceMissingError(error)+ ? createConversationParentMissingError(parentMessageId, error)+ : error instanceof Error+ ? error+ : new Error(String(error));+ await streamManager.publishStreamEvent(operationId, {+ data: formatErrorEventData(fatal, 'tool_message_persist'),+ stepIndex,+ type: 'error',+ });+ throw fatal;+ }++ newState.messages.push({+ content: result.content,+ role: 'tool',+ tool_call_id: toolPayload.id,+ });+ events.push({ id: toolPayload.id, result, type: 'tool_result' });+ toolResults.push({ data: result, toolCallId: toolPayload.id });+ }++ newState.lastModified = new Date().toISOString();++ return {+ events,+ newState,+ nextContext: {+ payload: {+ parentMessageId: toolMessageIds.at(-1) ?? parentMessageId,+ toolCount: toolsCalling.length,+ toolResults,+ },+ phase: 'tools_batch_result',+ session: {+ eventCount: events.length,+ messageCount: newState.messages.length,+ sessionId: operationId,+ status: 'running',+ stepCount: state.stepCount + 1,+ },+ },+ };+ },+/*** Resolve aborted tool calls* Create tool messages with 'aborted' intervention status for canceled tool callsdiff --git a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex 959af89fc55..378c1567adb 100644--- a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -3242,6 +3242,74 @@ describe('RuntimeExecutors', () => {});});+ describe('resolve_blocked_tools executor', () => {+ const createMockState = (overrides?: Partial<AgentState>): AgentState => ({+ cost: createMockCost(),+ createdAt: new Date().toISOString(),+ lastModified: new Date().toISOString(),+ maxSteps: 100,+ messages: [],+ metadata: {+ agentId: 'agent-123',+ threadId: 'thread-123',+ topicId: 'topic-123',+ },+ operationId: 'op-123',+ status: 'running',+ stepCount: 0,+ toolManifestMap: {},+ usage: createMockUsage(),+ ...overrides,+ });++ it('should create rejected tool messages and continue execution', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const instruction = {+ payload: {+ parentMessageId: 'assistant-msg-123',+ toolsCalling: [+ {+ apiName: 'bash',+ arguments: '{"command":"rm -rf /"}',+ id: 'tool-call-1',+ identifier: 'bash',+ type: 'builtin' as const,+ },+ ],+ },+ type: 'resolve_blocked_tools' as const,+ };++ const result = await executors.resolve_blocked_tools!(instruction, state);++ expect(mockToolExecutionService.executeTool).not.toHaveBeenCalled();+ expect(mockMessageModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-123',+ content: 'Blocked by security/privacy.',+ parentId: 'assistant-msg-123',+ pluginError: 'blocked_by_security_privacy',+ pluginIntervention: {+ rejectedReason: 'blocked_by_security_privacy',+ status: 'rejected',+ },+ role: 'tool',+ threadId: 'thread-123',+ tool_call_id: 'tool-call-1',+ topicId: 'topic-123',+ }),+ );+ expect(result.newState.status).toBe('running');+ expect(result.nextContext?.phase).toBe('tools_batch_result');+ expect(result.nextContext?.payload).toMatchObject({+ parentMessageId: 'msg-123',+ toolCount: 1,+ });+ });+ });+describe('resolve_aborted_tools executor', () => {const createMockState = (overrides?: Partial<AgentState>): AgentState => ({cost: createMockCost(),