🤯 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(agent-runtime): enforce scoped tool allowlists (#17717)
Rylan Cai71e353ac1f36
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex 9a2ef9de106..da85d737bfe 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -1,3 +1,4 @@+import { ToolNameResolver } from '@lobechat/context-engine';import {type ChatToolPayload,type ExtendedHumanInterventionConfig,@@ -26,6 +27,10 @@ import {} from '../types';import { shouldCompress } from '../utils/tokenCounter';+const TOOL_NOT_ALLOWED_CONTENT =+ 'Tool execution blocked because the tool is not allowed in the current execution scope.';+const TOOL_NOT_ALLOWED_REASON = 'tool_not_allowed';+/*** ChatAgent - The "Brain" of the chat agent*@@ -56,6 +61,25 @@ export class GeneralChatAgent implements Agent {: { allowedToolNames: this.config.allowedToolNames };}+ private partitionToolsByAllowList(toolsCalling: ChatToolPayload[]) {+ // An omitted allow-list preserves unrestricted behavior; an explicit empty list blocks all tools.+ if (this.config.allowedToolNames === undefined) {+ return { allowedTools: toolsCalling, blockedTools: [] };+ }++ const allowedToolNames = new Set(this.config.allowedToolNames);+ const toolNameResolver = new ToolNameResolver();+ const allowedTools: ChatToolPayload[] = [];+ const blockedTools: ChatToolPayload[] = [];++ for (const tool of toolsCalling) {+ const toolName = toolNameResolver.generate(tool.identifier, tool.apiName, tool.type);+ (allowedToolNames.has(toolName) ? allowedTools : blockedTools).push(tool);+ }++ return { allowedTools, blockedTools };+ }+/*** Get intervention configuration for a specific tool call*/@@ -515,9 +539,10 @@ export class GeneralChatAgent implements Agent {context.payload as GeneralAgentCallLLMResultPayload;if (hasToolsCalling && toolsCalling && toolsCalling.length > 0) {+ const { allowedTools, blockedTools } = this.partitionToolsByAllowList(toolsCalling);// Check which tools need human interventionconst [toolsNeedingIntervention, toolsToExecute] = await this.checkInterventionNeeded(- toolsCalling,+ allowedTools,state,);@@ -545,6 +570,19 @@ export class GeneralChatAgent implements Agent {}}+ // Resolve denied tools before an approval request parks the runtime.+ if (blockedTools.length > 0) {+ instructions.push({+ payload: {+ blockedContent: TOOL_NOT_ALLOWED_CONTENT,+ blockedReason: TOOL_NOT_ALLOWED_REASON,+ parentMessageId,+ toolsCalling: blockedTools,+ },+ type: 'resolve_blocked_tools',+ } satisfies AgentInstruction);+ }+// Request approval for tools that need intervention// Non-headless mode waits for human approval; headless mode returns blocked tool results.if (toolsNeedingIntervention.length > 0) {diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.tsindex 17a1443a8d9..5240af06d02 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -424,6 +424,118 @@ describe('GeneralChatAgent', () => {]);});+ it('should block every tool when allowedToolNames is empty', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ allowedToolNames: [],+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });+ const toolCall: ChatToolPayload = {+ apiName: 'runCommand',+ arguments: '{}',+ id: 'call-1',+ identifier: 'lobe-local-system',+ type: 'builtin',+ };++ const result = await agent.runner(+ createMockContext('llm_result', {+ hasToolsCalling: true,+ parentMessageId: 'msg-1',+ toolsCalling: [toolCall],+ }),+ createMockState(),+ );++ expect(result).toEqual([+ {+ payload: {+ blockedContent:+ 'Tool execution blocked because the tool is not allowed in the current execution scope.',+ blockedReason: 'tool_not_allowed',+ parentMessageId: 'msg-1',+ toolsCalling: [toolCall],+ },+ type: 'resolve_blocked_tools',+ },+ ]);+ });++ it('should execute allowed tools, resolve denied tools, then pause for approval', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ allowedToolNames: ['lobe-local-system____readFile', 'lobe-local-system____deleteFile'],+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });+ const readFile: ChatToolPayload = {+ apiName: 'readFile',+ arguments: '{}',+ id: 'call-read',+ identifier: 'lobe-local-system',+ type: 'builtin',+ };+ const deleteFile: ChatToolPayload = {+ apiName: 'deleteFile',+ arguments: '{}',+ id: 'call-delete',+ identifier: 'lobe-local-system',+ type: 'builtin',+ };+ const runCommand: ChatToolPayload = {+ apiName: 'runCommand',+ arguments: '{}',+ id: 'call-command',+ identifier: 'lobe-local-system',+ type: 'builtin',+ };++ const result = await agent.runner(+ createMockContext('llm_result', {+ hasToolsCalling: true,+ parentMessageId: 'msg-1',+ toolsCalling: [readFile, deleteFile, runCommand],+ }),+ createMockState({+ toolManifestMap: {+ 'lobe-local-system': {+ api: [+ { name: 'readFile' },+ { humanIntervention: 'require', name: 'deleteFile' },+ { name: 'runCommand' },+ ],+ identifier: 'lobe-local-system',+ type: 'builtin',+ },+ },+ }),+ );++ expect(result).toEqual([+ {+ payload: { parentMessageId: 'msg-1', toolCalling: readFile },+ type: 'call_tool',+ },+ {+ payload: {+ blockedContent:+ 'Tool execution blocked because the tool is not allowed in the current execution scope.',+ blockedReason: 'tool_not_allowed',+ parentMessageId: 'msg-1',+ toolsCalling: [runCommand],+ },+ type: 'resolve_blocked_tools',+ },+ {+ parentMessageId: 'msg-1',+ pendingToolsCalling: [deleteFile],+ reason: 'human_intervention_required',+ type: 'request_human_approve',+ },+ ]);+ });+it('should handle invalid JSON in tool arguments gracefully', async () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },diff --git a/packages/agent-runtime/src/agents/__tests__/GraphAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GraphAgent.test.tsindex 671c31d3920..72e98cf5e48 100644--- a/packages/agent-runtime/src/agents/__tests__/GraphAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GraphAgent.test.ts@@ -766,6 +766,50 @@ describe('GraphAgent', () => {).toEqual([readToolName, searchToolName]);});+ it('should reject a resolved tool call outside the active node allow-list', async () => {+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph: loadGoalLoopGraph(),+ modelRuntimeConfig: { model: 'gpt-4', provider: 'openai' },+ operationId: 'test-operation',+ });+ const state = createMockState({+ messages: [{ content: '/goal inspect workspace', role: 'user' }],+ });+ const writeToolCall = {+ apiName: 'write',+ arguments: '{}',+ id: 'call-write',+ identifier: 'workspace',+ type: 'builtin' as const,+ };++ expectCallLlm(await agent.runner(createContext('init'), state));++ const instruction = await agent.runner(+ createContext('llm_result', {+ hasToolsCalling: true,+ parentMessageId: 'assistant-msg-1',+ result: { content: '', tool_calls: [] },+ toolsCalling: [writeToolCall],+ }),+ state,+ );++ expect(instruction).toEqual([+ {+ payload: {+ blockedContent:+ 'Tool execution blocked because the tool is not allowed in the current execution scope.',+ blockedReason: 'tool_not_allowed',+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [writeToolCall],+ },+ type: 'resolve_blocked_tools',+ },+ ]);+ });+it('should not add a tool allow-list when delegating an unrestricted agent node', async () => {const graph = loadGoalLoopGraph();const planNode = graph.nodes.plan;diff --git a/packages/agent-runtime/src/executors/resolveTools.test.ts b/packages/agent-runtime/src/executors/resolveTools.test.tsindex 48961627f18..90bf0c12e52 100644--- a/packages/agent-runtime/src/executors/resolveTools.test.ts+++ b/packages/agent-runtime/src/executors/resolveTools.test.ts@@ -126,6 +126,43 @@ describe('resolveTools executors', () => {});});+ it('persists a caller-provided blocked reason and content', async () => {+ const instruction: Extract<AgentInstruction, { type: 'resolve_blocked_tools' }> = {+ payload: {+ blockedContent: 'Tool is outside the current execution scope.',+ blockedReason: 'tool_not_allowed',+ parentMessageId: 'assistant-msg-1',+ toolsCalling: [createToolCall()],+ },+ type: 'resolve_blocked_tools',+ };++ const result = await resolveBlockedTools(host)(instruction, createState());++ expect(createToolMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ content: 'Tool is outside the current execution scope.',+ pluginError: 'tool_not_allowed',+ pluginIntervention: {+ rejectedReason: 'tool_not_allowed',+ status: 'rejected',+ },+ pluginState: { reason: 'tool_not_allowed', type: 'blocked' },+ }),+ );+ expect(result.events).toContainEqual({+ id: 'tool-call-1',+ result: {+ content: 'Tool is outside the current execution scope.',+ error: 'tool_not_allowed',+ executionTime: 0,+ state: { reason: 'tool_not_allowed', type: 'blocked' },+ success: false,+ },+ type: 'tool_result',+ });+ });+it('persists aborted tools and completes the operation as user_aborted', async () => {const instruction: Extract<AgentInstruction, { type: 'resolve_aborted_tools' }> = {payload: {diff --git a/packages/agent-runtime/src/executors/resolveTools.ts b/packages/agent-runtime/src/executors/resolveTools.tsindex 2b6f3c11302..02c3a6e029c 100644--- a/packages/agent-runtime/src/executors/resolveTools.ts+++ b/packages/agent-runtime/src/executors/resolveTools.ts@@ -86,6 +86,8 @@ export const resolveBlockedTools =const topicId = operation.topicId ?? state.metadata?.topicId;const events: AgentEvent[] = [];const newState = structuredClone(state);+ const blockedContent = payload.blockedContent ?? BLOCKED_TOOL_CONTENT;+ const blockedReason = payload.blockedReason ?? BLOCKED_TOOL_ERROR;const toolResults: Array<{ data: ToolRunResult; toolCallId: string }> = [];const toolMessageIds: string[] = [];@@ -97,10 +99,13 @@ export const resolveBlockedTools =for (const toolPayload of payload.toolsCalling) {const result: ToolRunResult = {- content: BLOCKED_TOOL_CONTENT,- error: BLOCKED_TOOL_ERROR,+ content: blockedContent,+ error: blockedReason,executionTime: 0,- state: { type: 'blocked' },+ state: {+ ...(payload.blockedReason && { reason: blockedReason }),+ type: 'blocked',+ },success: false,};@@ -128,7 +133,7 @@ export const resolveBlockedTools =plugin: toolPayload as any,pluginError: result.error,pluginIntervention: {- rejectedReason: BLOCKED_TOOL_ERROR,+ rejectedReason: blockedReason,status: 'rejected',},pluginState: result.state,