Skip to content

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

✨ feat: support tool invention (#10182)

Arvin Xu4dca708d2cd1
diff --git a/packages/agent-runtime/src/core/InterventionChecker.ts b/packages/agent-runtime/src/core/InterventionChecker.ts
index ed5c13a9be4..0cfb62ddd3d 100644
--- a/packages/agent-runtime/src/core/InterventionChecker.ts
+++ b/packages/agent-runtime/src/core/InterventionChecker.ts
@@ -17,36 +17,25 @@ export class InterventionChecker {
* @returns Policy to apply
*/
static shouldIntervene(params: ShouldInterveneParams): HumanInterventionPolicy {
- const { config, toolArgs = {}, confirmedHistory = [], toolKey } = params;
+ const { config, toolArgs = {} } = params;
// No config means never intervene (auto-execute)
if (!config) return 'never';
// Simple policy string
if (typeof config === 'string') {
- // For 'first' policy, check if already confirmed
- if (config === 'first' && toolKey && confirmedHistory.includes(toolKey)) {
- return 'never';
- }
return config;
}
// Array of rules - find first matching rule
for (const rule of config) {
if (this.matchesRule(rule, toolArgs)) {
- const policy = rule.policy;
-
- // For 'first' policy, check if already confirmed
- if (policy === 'first' && toolKey && confirmedHistory.includes(toolKey)) {
- return 'never';
- }
-
- return policy;
+ return rule.policy;
}
}
- // No rule matched - default to always for safety
- return 'always';
+ // No rule matched - default to require for safety
+ return 'require';
}
/**
@@ -151,7 +140,7 @@ export class InterventionChecker {
}
/**
- * Generate simple hash of arguments for 'once' policy
+ * Generate simple hash of arguments for tool tracking
*
* @param args - Tool call arguments
* @returns Hash string
diff --git a/packages/agent-runtime/src/core/__tests__/InterventionChecker.test.ts b/packages/agent-runtime/src/core/__tests__/InterventionChecker.test.ts
index 771cf4f45b0..a71b6a86446 100644
--- a/packages/agent-runtime/src/core/__tests__/InterventionChecker.test.ts
+++ b/packages/agent-runtime/src/core/__tests__/InterventionChecker.test.ts
@@ -12,43 +12,16 @@ describe('InterventionChecker', () => {
it('should return the policy when config is a simple string', () => {
expect(InterventionChecker.shouldIntervene({ config: 'never', toolArgs: {} })).toBe('never');
- expect(InterventionChecker.shouldIntervene({ config: 'always', toolArgs: {} })).toBe(
- 'always',
+ expect(InterventionChecker.shouldIntervene({ config: 'require', toolArgs: {} })).toBe(
+ 'require',
);
- expect(InterventionChecker.shouldIntervene({ config: 'first', toolArgs: {} })).toBe('first');
- });
-
- it('should handle "first" policy with confirmed history', () => {
- const toolKey = 'web-browsing/crawlSinglePage';
- const confirmedHistory = [toolKey];
-
- const result = InterventionChecker.shouldIntervene({
- config: 'first',
- toolArgs: {},
- confirmedHistory,
- toolKey,
- });
- expect(result).toBe('never');
- });
-
- it('should require intervention for "first" policy without confirmation', () => {
- const toolKey = 'web-browsing/crawlSinglePage';
- const confirmedHistory: string[] = [];
-
- const result = InterventionChecker.shouldIntervene({
- config: 'first',
- toolArgs: {},
- confirmedHistory,
- toolKey,
- });
- expect(result).toBe('first');
});
it('should match rules in order and return first match', () => {
const config: HumanInterventionConfig = [
{ match: { command: 'ls:*' }, policy: 'never' },
- { match: { command: 'git commit:*' }, policy: 'first' },
- { policy: 'always' }, // Default rule
+ { match: { command: 'git commit:*' }, policy: 'require' },
+ { policy: 'require' }, // Default rule
];
expect(InterventionChecker.shouldIntervene({ config, toolArgs: { command: 'ls:' } })).toBe(
@@ -56,20 +29,20 @@ describe('InterventionChecker', () => {
);
expect(
InterventionChecker.shouldIntervene({ config, toolArgs: { command: 'git commit:' } }),
- ).toBe('first');
+ ).toBe('require');
expect(
InterventionChecker.shouldIntervene({ config, toolArgs: { command: 'rm -rf /' } }),
- ).toBe('always');
+ ).toBe('require');
});
- it('should return always as default when no rule matches', () => {
+ it('should return require as default when no rule matches', () => {
const config: HumanInterventionConfig = [{ match: { command: 'ls:*' }, policy: 'never' }];
const result = InterventionChecker.shouldIntervene({
config,
toolArgs: { command: 'rm -rf /' },
});
- expect(result).toBe('always');
+ expect(result).toBe('require');
});
it('should handle multiple parameter matching', () => {
@@ -81,7 +54,7 @@ describe('InterventionChecker', () => {
},
policy: 'never',
},
- { policy: 'always' },
+ { policy: 'require' },
];
// Both match
@@ -104,20 +77,20 @@ describe('InterventionChecker', () => {
path: '/tmp/file.ts',
},
}),
- ).toBe('always');
+ ).toBe('require');
});
it('should handle default rule without match', () => {
const config: HumanInterventionConfig = [
{ match: { command: 'ls:*' }, policy: 'never' },
- { policy: 'first' }, // Default rule
+ { policy: 'require' }, // Default rule
];
const result = InterventionChecker.shouldIntervene({
config,
toolArgs: { command: 'anything' },
});
- expect(result).toBe('first');
+ expect(result).toBe('require');
});
});
@@ -249,10 +222,10 @@ describe('InterventionChecker', () => {
it('should handle Bash tool scenario', () => {
const config: HumanInterventionConfig = [
{ match: { command: 'ls:*' }, policy: 'never' },
- { match: { command: 'git add:*' }, policy: 'first' },
- { match: { command: 'git commit:*' }, policy: 'first' },
- { match: { command: 'rm:*' }, policy: 'always' },
- { policy: 'always' },
+ { match: { command: 'git add:*' }, policy: 'require' },
+ { match: { command: 'git commit:*' }, policy: 'require' },
+ { match: { command: 'rm:*' }, policy: 'require' },
+ { policy: 'require' },
];
// Safe commands - never
@@ -260,27 +233,27 @@ describe('InterventionChecker', () => {
'never',
);
- // Git commands - first
+ // Git commands - require
expect(
InterventionChecker.shouldIntervene({ config, toolArgs: { command: 'git add:.' } }),
- ).toBe('first');
+ ).toBe('require');
expect(
InterventionChecker.shouldIntervene({ config, toolArgs: { command: 'git commit:-m' } }),
- ).toBe('first');
+ ).toBe('require');
- // Dangerous commands - always
+ // Dangerous commands - require
expect(InterventionChecker.shouldIntervene({ config, toolArgs: { command: 'rm:-rf' } })).toBe(
- 'always',
+ 'require',
);
expect(
InterventionChecker.shouldIntervene({ config, toolArgs: { command: 'npm install' } }),
- ).toBe('always');
+ ).toBe('require');
});
it('should handle LocalSystem tool scenario', () => {
const config: HumanInterventionConfig = [
{ match: { path: '/Users/project/*' }, policy: 'never' },
- { policy: 'first' },
+ { policy: 'require' },
];
// Project directory - never
@@ -291,44 +264,18 @@ describe('InterventionChecker', () => {
}),
).toBe('never');
- // Outside project - first
+ // Outside project - require
expect(
InterventionChecker.shouldIntervene({ config, toolArgs: { path: '/tmp/file.ts' } }),
- ).toBe('first');
+ ).toBe('require');
});
it('should handle Web Browsing tool with simple policy', () => {
- const config: HumanInterventionConfig = 'always';
+ const config: HumanInterventionConfig = 'require';
expect(
InterventionChecker.shouldIntervene({ config, toolArgs: { url: 'https://example.com' } }),
- ).toBe('always');
- });
-
- it('should handle first policy with confirmation history', () => {
- const config: HumanInterventionConfig = [
- { match: { command: 'git add:*' }, policy: 'first' },
- { policy: 'always' },
- ];
-
- const toolKey = 'bash/bash#abc123';
- const args = { command: 'git add:.' };
-
- // First time - requires intervention
- expect(
- InterventionChecker.shouldIntervene({
- config,
- toolArgs: args,
- confirmedHistory: [],
- toolKey,
- }),
- ).toBe('first');
-
- // After confirmation - never
- const confirmedHistory = [toolKey];
- expect(
- InterventionChecker.shouldIntervene({ config, toolArgs: args, confirmedHistory, toolKey }),
- ).toBe('never');
+ ).toBe('require');
});
});
});
diff --git a/packages/agent-runtime/src/core/__tests__/runtime.test.ts b/packages/agent-runtime/src/core/__tests__/runtime.test.ts
index e554d9bd524..3274a421ddc 100644
--- a/packages/agent-runtime/src/core/__tests__/runtime.test.ts
+++ b/packages/agent-runtime/src/core/__tests__/runtime.test.ts
@@ -1,3 +1,4 @@
+import { ChatToolPayload } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
import {
@@ -344,9 +345,11 @@ describe('AgentRuntime', () => {
type: 'request_human_approve',
pendingToolsCalling: [
{
+ apiName: 'test_tool',
+ arguments: '{}',
id: 'call_123',
- type: 'function',
- function: { name: 'test_tool', arguments: '{}' },
+ identifier: 'test_tool',
+ type: 'default',
},
],
}),
@@ -357,14 +360,11 @@ describe('AgentRuntime', () => {
const result = await runtime.step(state);
- expect(result.events).toHaveLength(2);
+ expect(result.events).toHaveLength(1);
expect(result.events[0]).toMatchObject({
type: 'human_approve_required',
sessionId: 'test-session',
});
- expect(result.events[1]).toMatchObject({
- type: 'tool_pending',
- });
expect(result.newState.status).toBe('waiting_for_human');
expect(result.newState.pendingToolsCalling).toBeDefined();
@@ -947,12 +947,29 @@ describe('AgentRuntime', () => {
case 'llm_result':
const llmPayload = context.payload as { result: any; hasToolCalls: boolean };
if (llmPayload.hasToolCalls) {
+ // Convert OpenAI format tool_calls to ChatToolPayload format
+ const pendingToolsCalling = llmPayload.result.tool_calls.map((tc: any) => ({
+ apiName: tc.function.name,
+ arguments: tc.function.arguments,
+ id: tc.id,
+ identifier: tc.function.name,
+ type: 'default' as const,
+ }));
return Promise.resolve({
+ pendingToolsCalling,
type: 'request_human_approve',
- pendingToolsCalling: llmPayload.result.tool_calls,
});
}
return Promise.resolve({ type: 'finish', reason: 'completed', reasonDetail: 'Done' });
+ case 'human_approved_tool':
+ const approvedPayload = context.payload as { approvedToolCall: ChatToolPayload };
+ return Promise.resolve({
+ payload: {
+ parentMessageId: 'user-msg-id',
+ toolCalling: approvedPayload.approvedToolCall,
+ },
+ type: 'call_tool',
+ });
case 'tool_result':
return Promise.resolve({ type: 'call_llm', payload: { messages: state.messages } });
default:
@@ -1021,10 +1038,10 @@ describe('AgentRuntime', () => {
// Step 2: Approve and execute tool call
const pendingToolCall = result.newState.pendingToolsCalling![0];
const toolCall = {
+ apiName: pendingToolCall.apiName,
+ arguments: pendingToolCall.arguments,
id: pendingToolCall.id,
- apiName: pendingToolCall.function.name,
- identifier: pendingToolCall.function.name,
- arguments: pendingToolCall.function.arguments,
+ identifier: pendingToolCall.identifier,
type: 'default' as const,
};
result = await runtime.approveToolCall(result.newState, toolCall);
@@ -1203,9 +1220,11 @@ describe('AgentRuntime', () => {
{
pendingToolsCalling: [
{
+ apiName: 'danger_tool',
+ arguments: '{}',
id: 'call_danger',
- type: 'function' as const,
- function: { name: 'danger_tool', arguments: '{}' },
+ identifier: 'danger_tool',
+ type: 'default' as const,
},
],
type: 'request_human_approve' as const,
@@ -1233,7 +1252,7 @@ describe('AgentRuntime', () => {
// Should have pending tool calls
expect(result.newState.pendingToolsCalling).toHaveLength(1);
- expect(result.newState.pendingToolsCalling![0].function.name).toBe('danger_tool');
+ expect(result.newState.pendingToolsCalling![0].apiName).toBe('danger_tool');
// Should have both tool_result and human_approve_required events
expect(result.events).toContainEqual(expect.objectContaining({ type: 'tool_result' }));
diff --git a/packages/agent-runtime/src/core/runtime.ts b/packages/agent-runtime/src/core/runtime.ts
index fcf4a9efdd1..65ead905200 100644
--- a/packages/agent-runtime/src/core/runtime.ts
+++ b/packages/agent-runtime/src/core/runtime.ts
@@ -85,12 +85,17 @@ export class AgentRuntime {
// Handle human approved tool calls
if (runtimeContext.phase === 'human_approved_tool') {
- const approvedPayload = runtimeContext.payload as { approvedToolCall: ChatToolPayload };
+ const approvedPayload = runtimeContext.payload as {
+ approvedToolCall: ChatToolPayload;
+ parentMessageId: string;
+ skipCreateToolMessage: boolean;
+ };
const toolCalling = approvedPayload.approvedToolCall;
rawInstructions = {
payload: {
- parentMessageId: '', // Not required for approval flow
+ parentMessageId: approvedPayload.parentMessageId,
+ skipCreateToolMessage: approvedPayload.skipCreateToolMessage,
toolCalling,
},
type: 'call_tool',
@@ -538,7 +543,6 @@ export class AgentRuntime {
sessionId: newState.sessionId,
type: 'human_approve_required',
},
- { toolCalls: pendingToolsCalling, type: 'tool_pending' },
];
return { events, newState };
diff --git a/packages/agent-runtime/src/types/event.ts b/packages/agent-runtime/src/types/event.ts
index 5e39c68a041..ed15e932864 100644
--- a/packages/agent-runtime/src/types/event.ts
+++ b/packages/agent-runtime/src/types/event.ts
@@ -1,5 +1,6 @@
/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
import type { AgentState, ToolsCalling } from './state';
+import { ChatToolPayload } from '@/types/message';
export interface AgentEventInit {
type: 'init';
@@ -33,7 +34,7 @@ export interface AgentEventToolResult {
export interface AgentEventHumanApproveRequired {
type: 'human_approve_required';
- pendingToolsCalling: ToolsCalling[];
+ pendingToolsCalling: ChatToolPayload[];
sessionId: string;
}
diff --git a/packages/agent-runtime/src/types/generalAgent.ts b/packages/agent-runtime/src/types/generalAgent.ts
index 3de8a1fe825..1874af3f522 100644
--- a/packages/agent-runtime/src/types/generalAgent.ts
+++ b/packages/agent-runtime/src/types/generalAgent.ts
@@ -18,6 +18,7 @@ export interface GeneralAgentCallLLMResultPayload {
export interface GeneralAgentCallingToolInstructionPayload {
parentMessageId: string;
+ skipCreateToolMessage?: boolean;
toolCalling: ChatToolPayload;
}
diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.ts
index 4b7bee3d2c2..3ea8dcc4ec6 100644
--- a/packages/agent-runtime/src/types/instruction.ts
+++ b/packages/agent-runtime/src/types/instruction.ts
@@ -1,7 +1,7 @@
import { ChatToolPayload, ModelUsage } from '@lobechat/types';
import type { FinishReason } from './event';
-import { AgentState, ToolRegistry, ToolsCalling } from './state';
+import { AgentState, ToolRegistry } from './state';
import type { Cost, CostCalculationContext, Usage } from './usage';
/**
@@ -137,8 +137,9 @@ export interface AgentInstructionRequestHumanSelect {
}
export interface AgentInstructionRequestHumanApprove {
- pendingToolsCalling: ToolsCalling[];
+ pendingToolsCalling: ChatToolPayload[];
reason?: string;
+ skipCreateToolMessage?: boolean;
type: 'request_human_approve';
}
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index dd4131e2c19..1496488ee9e 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -1,4 +1,6 @@
/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
+import { ChatToolPayload } from '@/types/message';
+
import type { Cost, CostLimit, Usage } from './usage';
/**
@@ -49,7 +51,7 @@ export interface AgentState {
* When status is 'waiting_for_human', this stores pending requests
* for human-in-the-loop operations.
*/
- pendingToolsCalling?: ToolsCalling[];
+ pendingToolsCalling?: ChatToolPayload[];
pendingHumanPrompt?: { metadata?: Record<string, unknown>; prompt: string };
pendingHumanSelect?: {
metadata?: Record<string, unknown>;
diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
index 8b3c0a55678..9fea98d830b 100644
--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts
+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
@@ -427,11 +427,14 @@ export class FlatListBuilder {
if (toolMsg.error) result.error = toolMsg.error;
if (toolMsg.pluginState) result.state = toolMsg.pluginState;
- return {
+ const toolWithResult: ChatToolPayloadWithResult = {
...tool,
+ intervention: toolMsg.pluginIntervention,
result,
result_msg_id: toolMsg.id,
};
+
+ return toolWithResult;
}
return tool;
}) || [];
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index a3c201ffd5e..6f30ad67f14 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -97,6 +97,7 @@ export class MessageModel {
type: messagePlugins.type,
},
pluginError: messagePlugins.error,
+ pluginIntervention: messagePlugins.intervention,
pluginState: messagePlugins.state,
translate: {
@@ -462,6 +463,7 @@ export class MessageModel {
provider: fromProvider,
files,
plugin,
+ pluginIntervention,
pluginState,
fileChunks,
ragQueryId,
@@ -496,6 +498,7 @@ export class MessageModel {
arguments: plugin?.arguments,
id,
identifier: plugin?.identifier,
+ intervention: pluginIntervention,
state: pluginState,
toolCallId: message.tool_call_id,
type: plugin?.type,
diff --git a/packages/types/src/message/common/base.ts b/packages/types/src/message/common/base.ts
index 20b78cd0255..a677485725e 100644
--- a/packages/types/src/message/common/base.ts
+++ b/packages/types/src/message/common/base.ts
@@ -9,13 +9,13 @@ import { ErrorType } from '../../fetch';
*/
export interface ChatMessageError {
body?: any;
- message: string;
+ message?: string;
type: ErrorType | IPluginErrorType | ILobeAgentRuntimeErrorType;
}
export const ChatMessageErrorSchema = z.object({
body: z.any().optional(),
- message: z.string(),
+ message: z.string().optional(),
type: z.union([z.string(), z.number()]),
});
diff --git a/packages/types/src/message/common/tools.ts b/packages/types/src/message/common/tools.ts
index 29eaaa138c1..8cd28fcb55e 100644
--- a/packages/types/src/message/common/tools.ts
+++ b/packages/types/src/message/common/tools.ts
@@ -4,10 +4,22 @@ import { z } from 'zod';
import { LobeToolRenderType } from '../../tool';
+// ToolIntervention must be defined first to avoid circular dependency
+export interface ToolIntervention {
+ rejectedReason?: string;
+ status?: 'pending' | 'approved' | 'rejected' | 'none';
+}
+
+export const ToolInterventionSchema = z.object({
+ rejectedReason: z.string().optional(),
+ status: z.enum(['pending', 'approved', 'rejected', 'none']).optional(),
+});
+
export interface ChatPluginPayload {
apiName: string;
arguments: string;
identifier: string;
+ intervention?: ToolIntervention;
type: LobeToolRenderType;
}
@@ -16,6 +28,7 @@ export interface ChatToolPayload {
arguments: string;
id: string;
identifier: string;
+ intervention?: ToolIntervention;
result_msg_id?: string;
type: LobeToolRenderType;
}
@@ -34,7 +47,9 @@ export interface ChatToolResult {
* Chat tool payload with merged execution result
*/
export interface ChatToolPayloadWithResult extends ChatToolPayload {
+ intervention?: ToolIntervention;
result?: ChatToolResult;
+ result_msg_id?: string;
}
export interface ToolsCallingContext {
@@ -91,6 +106,7 @@ export const ChatToolPayloadSchema = z.object({
arguments: z.string(),
id: z.string(),
identifier: z.string(),
+ intervention: ToolInterventionSchema.optional(),
result_msg_id: z.string().optional(),
type: z.string(),
});
@@ -103,13 +119,3 @@ export interface ChatMessagePluginError {
message: string;
type: IPluginErrorType;
}
-
-export interface ToolIntervention {
- rejectedReason?: string;
- status?: 'pending' | 'approved' | 'rejected' | 'none';
-}
-
-export const ToolInterventionSchema = z.object({
- rejectedReason: z.string().optional(),
- status: z.enum(['pending', 'approved', 'rejected', 'none']).optional(),
-});
diff --git a/packages/types/src/message/ui/chat.ts b/packages/types/src/message/ui/chat.ts
index b2dd8c8eb9a..f2634b038d2 100644
--- a/packages/types/src/message/ui/chat.ts
+++ b/packages/types/src/message/ui/chat.ts
@@ -8,7 +8,12 @@ import {
ModelReasoning,
ModelUsage,
} from '../common';
-import { ChatPluginPayload, ChatToolPayload, ChatToolPayloadWithResult } from '../common/tools';
+import {
+ ChatPluginPayload,
+ ChatToolPayload,
+ ChatToolPayloadWithResult,
+ ToolIntervention,
+} from '../common/tools';
import { ChatMessageExtra } from './extra';
import { ChatFileChunk } from './rag';
import { ChatVideoItem } from './video';
@@ -95,6 +100,7 @@ export interface UIChatMessage {
performance?: ModelPerformance;
plugin?: ChatPluginPayload;
pluginError?: any;
+ pluginIntervention?: ToolIntervention;
pluginState?: any;
provider?: string | null;
/**
diff --git a/packages/types/src/tool/intervention.ts b/packages/types/src/tool/intervention.ts
index 77a26438d3e..67860e630a8 100644
--- a/packages/types/src/tool/intervention.ts
+++ b/packages/types/src/tool/intervention.ts
@@ -5,10 +5,9 @@ import { z } from 'zod';
*/
export type HumanInterventionPolicy =
| 'never' // Never intervene, auto-execute
- | 'always' // Always require intervention
- | 'first'; // Require intervention on first call only
+ | 'require'; // Always require intervention
-export const HumanInterventionPolicySchema = z.enum(['never', 'always', 'first']);
+export const HumanInterventionPolicySchema = z.enum(['never', 'require']);
/**
* Argument Matcher for parameter-level filtering
diff --git a/packages/types/src/user/settings/tool.ts b/packages/types/src/user/settings/tool.ts
index c0090e0ac2b..d73f05c138d 100644
--- a/packages/types/src/user/settings/tool.ts
+++ b/packages/types/src/user/settings/tool.ts
@@ -1,42 +1,29 @@
-import type { HumanInterventionConfig } from '../../tool';
-
export interface UserToolConfig {
+ /**
+ * Tool approval mode
+ * - auto-run: Automatically approve all tools without user consent
+ * - allow-list: Only approve tools in the allow list
+ * - manual: Require manual approval for each tool execution
+ */
+ approvalMode?: 'auto-run' | 'allow-list' | 'manual';
+
dalle: {
autoGenerate: boolean;
};
+
/**
- * Human intervention configuration
+ * Tool intervention configuration
*/
humanIntervention?: {
/**
- * List of confirmed tool calls (for 'once' policy)
- * Format: "identifier/apiName" or "identifier/apiName#argsHash"
+ * Allow list of approved tools (used in 'allow-list' mode)
+ * Format: "identifier/apiName"
*
* Examples:
* - "web-browsing/crawlSinglePage"
- * - "bash/bash#a1b2c3d4"
- */
- confirmed?: string[];
-
- /**
- * Whether human intervention is enabled globally
- * @default true
- */
- enabled: boolean;
-
- /**
- * Per-tool intervention policy overrides
- * Key format: "identifier/apiName"
- *
- * Example:
- * {
- * "web-browsing/crawlSinglePage": "confirm",
- * "bash/bash": [
- * { match: { command: "git add:*" }, policy: "auto" },
- * { policy: "confirm" }
- * ]
- * }
+ * - "bash/bash"
+ * - "search/search"
*/
- overrides?: Record<string, HumanInterventionConfig>;
+ allowList?: string[];
};
}
diff --git a/src/features/Conversation/Messages/Group/GroupChildren.tsx b/src/features/Conversation/Messages/Group/GroupChildren.tsx
index e0a1f1a1a00..9f8dad800c0 100644
--- a/src/features/Conversation/Messages/Group/GroupChildren.tsx
+++ b/src/features/Conversation/Messages/Group/GroupChildren.tsx
@@ -1,9 +1,10 @@
import { AssistantContentBlock } from '@lobechat/types';
import { createStyles } from 'antd-style';
import isEqual from 'fast-deep-equal';
-import { memo } from 'react';
+import { memo, useMemo } from 'react';
import { Flexbox } from 'react-layout-kit';
+import { GroupMessageContext } from './GroupContext';
import GroupItem from './GroupItem';
const useStyles = createStyles(({ css }) => {
@@ -28,21 +29,25 @@ const GroupChildren = memo<GroupChildrenProps>(
({ blocks, contentId, disableEditing, messageIndex, id }) => {
const { styles } = useStyles();
+ const contextValue = useMemo(() => ({ assistantGroupId: id }), [id]);
+
return (
- <Flexbox className={styles.container} gap={8}>
- {blocks.map((item, index) => {
- return (
- <GroupItem
- {...item}
- contentId={contentId}
- disableEditing={disableEditing}
- index={index}
- key={`${id}_${index}`}
- messageIndex={messageIndex}
- />
- );
- })}
- </Flexbox>
+ <GroupMessageContext value={contextValue}>
+ <Flexbox className={styles.container} gap={8}>
+ {blocks.map((item, index) => {
+ return (
+ <GroupItem
+ {...item}
+ contentId={contentId}
+ disableEditing={disableEditing}
+ index={index}
+ key={`${id}_${index}`}
+ messageIndex={messageIndex}
+ />
+ );
+ })}
+ </Flexbox>
+ </GroupMessageContext>
);
},
isEqual,
diff --git a/src/features/Conversation/Messages/Group/GroupContext.tsx b/src/features/Conversation/Messages/Group/GroupContext.tsx
new file mode 100644
index 00000000000..0a68aadf6b3
--- /dev/null
+++ b/src/features/Conversation/Messages/Group/GroupContext.tsx
@@ -0,0 +1,15 @@
+import { createContext, useContext } from 'react';
+
+interface GroupMessageContextValue {
+ assistantGroupId: string;
+}
+
+export const GroupMessageContext = createContext<GroupMessageContextValue | null>(null);
+
+export const useGroupMessage = () => {
+ const context = useContext(GroupMessageContext);
+ if (!context) {
+ throw new Error('useGroupMessage must be used within GroupMessageContext');
+ }
+ return context;
+};
diff --git a/src/features/Conversation/Messages/Group/Tool/Inspector/BuiltinPluginTitle.tsx b/src/features/Conversation/Messages/Group/Tool/Inspector/BuiltinPluginTitle.tsx
index 594857b77f4..333868a40c9 100644
--- a/src/features/Conversation/Messages/Group/Tool/Inspector/BuiltinPluginTitle.tsx
+++ b/src/features/Conversation/Messages/Group/Tool/Inspector/BuiltinPluginTitle.tsx
@@ -23,20 +23,18 @@ export const useStyles = createStyles(({ css, token }) => ({
interface BuiltinPluginTitleProps {
apiName: string;
- hasResult?: boolean;
icon?: ReactNode;
identifier: string;
index: number;
+ isLoading?: boolean;
messageId: string;
title: string;
toolCallId: string;
}
-const BuiltinPluginTitle = memo<BuiltinPluginTitleProps>(({ apiName, title, hasResult }) => {
+const BuiltinPluginTitle = memo<BuiltinPluginTitleProps>(({ apiName, title, isLoading }) => {
const { styles } = useStyles();
- const isLoading = !hasResult;
-
return (
<Flexbox align={'center'} className={isLoading ? styles.shinyText : ''} gap={4} horizontal>
<div>{title}</div>
diff --git a/src/features/Conversation/Messages/Group/Tool/Inspector/ToolTitle.tsx b/src/features/Conversation/Messages/Group/Tool/Inspector/ToolTitle.tsx
index 780842a9956..ad941941beb 100644
--- a/src/features/Conversation/Messages/Group/Tool/Inspector/ToolTitle.tsx
+++ b/src/features/Conversation/Messages/Group/Tool/Inspector/ToolTitle.tsx
@@ -31,20 +31,18 @@ export const useStyles = createStyles(({ css, token }) => ({
interface ToolTitleProps {
apiName: string;
- hasResult?: boolean;
identifier: string;
index: number;
+ isLoading?: boolean;
messageId: string;
toolCallId: string;
}
const ToolTitle = memo<ToolTitleProps>(
- ({ identifier, apiName, hasResult, index, toolCallId, messageId }) => {
+ ({ identifier, apiName, isLoading, index, toolCallId, messageId }) => {
const { t } = useTranslation('plugin');
const { styles } = useStyles();
- const isLoading = !hasResult;
-
const pluginMeta = useToolStore(toolSelectors.getMetaById(identifier), isEqual);
const plugins = useMemo(
@@ -69,9 +67,9 @@ const ToolTitle = memo<ToolTitleProps>(
return (
<BuiltinPluginTitle
{...builtinPluginTitle}
- hasResult={hasResult}
identifier={identifier}
index={index}
+ isLoading={isLoading}
messageId={messageId}
toolCallId={toolCallId}
/>
diff --git a/src/features/Conversation/Messages/Group/Tool/Inspector/index.tsx b/src/features/Conversation/Messages/Group/Tool/Inspector/index.tsx
index b196427bd7e..adef4be66c9 100644
--- a/src/features/Conversation/Messages/Group/Tool/Inspector/index.tsx
+++ b/src/features/Conversation/Messages/Group/Tool/Inspector/index.tsx
@@ -1,12 +1,13 @@
-import { ActionIcon } from '@lobehub/ui';
+import { ActionIcon, Icon, Tooltip } from '@lobehub/ui';
import { createStyles } from 'antd-style';
-import { Check, LayoutPanelTop, LogsIcon, LucideBug, LucideBugOff, X } from 'lucide-react';
+import { Ban, Check, LayoutPanelTop, LogsIcon, LucideBug, LucideBugOff, X } from 'lucide-react';
import { CSSProperties, memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Flexbox } from 'react-layout-kit';
import { LOADING_FLAT } from '@/const/message';
import { shinyTextStylish } from '@/styles/loading';
+import { ToolIntervention } from '@/types/message';
import Debug from './Debug';
import Settings from './Settings';
@@ -66,6 +67,7 @@ interface InspectorProps {
id: string;
identifier: string;
index: number;
+ intervention?: ToolIntervention;
messageId: string;
result?: { content: string | null; error?: any; state?: any };
setShowPluginRender: (show: boolean) => void;
@@ -91,6 +93,7 @@ const Inspectors = memo<InspectorProps>(
showPluginRender,
setShowPluginRender,
type,
+ intervention,
}) => {
const { t } = useTranslation('plugin');
const { styles, theme } = useStyles();
@@ -102,6 +105,11 @@ const Inspectors = memo<InspectorProps>(
const hasResult = hasSuccessResult || hasError;
+ const isPending = intervention?.status === 'pending';
+ const isReject = intervention?.status === 'rejected';
+ const isTitleLoading = !hasResult && !isPending;
+
+ const showCustomPluginRender = showRender && !isPending && !isReject;
return (
<Flexbox className={styles.container} gap={4}>
<Flexbox align={'center'} distribution={'space-between'} gap={8} horizontal>
@@ -117,16 +125,16 @@ const Inspectors = memo<InspectorProps>(
>
<ToolTitle
apiName={apiName}
- hasResult={hasResult}
identifier={identifier}
index={index}
+ isLoading={isTitleLoading}
messageId={messageId}
toolCallId={id}
/>
</Flexbox>
<Flexbox align={'center'} gap={8} horizontal>
<Flexbox className={styles.actions} horizontal>
- {showRender && (
+ {showCustomPluginRender && (
<ActionIcon
icon={showPluginRender ? LogsIcon : LayoutPanelTop}
onClick={() => {
@@ -148,10 +156,14 @@ const Inspectors = memo<InspectorProps>(
</Flexbox>
{hasResult && (
<Flexbox align={'center'} gap={4} horizontal style={{ fontSize: 12 }}>
- {hasError ? (
- <X color={theme.colorError} size={14} />
+ {isReject ? (
+ <Tooltip title={t('tool.intervention.toolRejected', { ns: 'chat' })}>
+ <Icon color={theme.colorTextTertiary} icon={Ban} />
+ </Tooltip>
+ ) : hasError ? (
+ <Icon color={theme.colorError} icon={X} />
) : (
- <Check color={theme.colorSuccess} size={14} />
+ <Icon color={theme.colorSuccess} icon={Check} />
)}
</Flexbox>
)}
diff --git a/src/features/Conversation/Messages/Group/Tool/Render/Arguments/index.tsx b/src/features/Conversation/Messages/Group/Tool/Render/Arguments/index.tsx
index 5aa94ab746e..f3747d8830c 100644
--- a/src/features/Conversation/Messages/Group/Tool/Render/Arguments/index.tsx
+++ b/src/features/Conversation/Messages/Group/Tool/Render/Arguments/index.tsx
@@ -115,18 +115,20 @@ const Arguments = memo<ArgumentsProps>(({ arguments: args = '', shine, actions }
{actions}
</Flexbox>
)}
- {Object.entries(displayArgs).map(([key, value]) => {
- return (
- <ObjectEntity
- editable={false}
- hasMinWidth={hasMinWidth}
- key={key}
- objectKey={key}
- shine={shine}
- value={value}
- />
- );
- })}
+ <Flexbox>
+ {Object.entries(displayArgs).map(([key, value]) => {
+ return (
+ <ObjectEntity
+ editable={false}
+ hasMinWidth={hasMinWidth}
+ key={key}
+ objectKey={key}
+ shine={shine}
+ value={value}
+ />
+ );
+ })}
+ </Flexbox>
</div>
);
});
diff --git a/src/features/Conversation/Messages/Group/Tool/Render/Intervention/ApprovalActions.tsx b/src/features/Conversation/Messages/Group/Tool/Render/Intervention/ApprovalActions.tsx
new file mode 100644
index 00000000000..1680c916830
--- /dev/null
+++ b/src/features/Conversation/Messages/Group/Tool/Render/Intervention/ApprovalActions.tsx
@@ -0,0 +1,143 @@
+import { Button, Dropdown } from '@lobehub/ui';
+import { Input, Popover, Space } from 'antd';
+import { ChevronDown } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useGroupMessage } from '@/features/Conversation/Messages/Group/GroupContext';
+import { useChatStore } from '@/store/chat';
+import { useUserStore } from '@/store/user';
+
+import { ApprovalMode } from './index';
+
+interface ApprovalActionsProps {
+ apiName: string;
+ approvalMode: ApprovalMode;
+ identifier: string;
+ messageId: string;
+ toolCallId: string;
+}
+
+const ApprovalActions = memo<ApprovalActionsProps>(
+ ({ approvalMode, messageId, identifier, apiName }) => {
+ const { t } = useTranslation(['chat', 'common']);
+ const [rejectReason, setRejectReason] = useState('');
+ const [rejectPopoverOpen, setRejectPopoverOpen] = useState(false);
+ const [rejectLoading, setRejectLoading] = useState(false);
+ const [approveLoading, setApproveLoading] = useState(false);
+
+ const { assistantGroupId } = useGroupMessage();
+ const [approveToolIntervention, rejectToolIntervention] = useChatStore((s) => [
+ s.approveToolCalling,
+ s.rejectToolCalling,
+ ]);
+ const addToolToAllowList = useUserStore((s) => s.addToolToAllowList);
+
+ const handleApprove = async (remember?: boolean) => {
+ setApproveLoading(true);
+ try {
+ // 1. Update intervention status
+ await approveToolIntervention(messageId, assistantGroupId);
+
+ // 2. If remembered, add to allowList
+ if (remember) {
+ const toolKey = `${identifier}/${apiName}`;
+ await addToolToAllowList(toolKey);
+ }
+ } finally {
+ setApproveLoading(false);
+ }
+ };
+
+ const handleReject = async (reason?: string) => {
+ setRejectLoading(true);
+ await rejectToolIntervention(messageId, reason);
+ setRejectLoading(false);
+ setRejectPopoverOpen(false);
+ setRejectReason('');
+ };
+
+ return (
+ <Flexbox gap={8} horizontal>
+ <Popover
+ arrow={false}
+ content={
+ <Flexbox gap={12} style={{ width: 400 }}>
+ <Flexbox align={'center'} horizontal justify={'space-between'}>
+ <div>{t('tool.intervention.rejectTitle')}</div>
+
+ <Button
+ loading={rejectLoading}
+ onClick={() => handleReject(rejectReason)}
+ size="small"
+ type="primary"
+ >
+ {t('confirm', { ns: 'common' })}
+ </Button>
+ </Flexbox>
+ <Input.TextArea
+ autoFocus
+ onChange={(e) => setRejectReason(e.target.value)}
+ placeholder={t('tool.intervention.rejectReasonPlaceholder')}
+ rows={3}
+ value={rejectReason}
+ variant={'filled'}
+ />
+ </Flexbox>
+ }
+ onOpenChange={(open) => {
+ if (rejectLoading) return;
+
+ setRejectPopoverOpen(open);
+ }}
+ open={rejectPopoverOpen}
+ placement="bottomRight"
+ trigger="click"
+ >
+ <Button size="small" type="default">
+ {t('tool.intervention.reject')}
+ </Button>
+ </Popover>
+
+ {approvalMode === 'allow-list' ? (
+ <Space.Compact>
+ <Button
+ loading={approveLoading}
+ onClick={() => handleApprove(true)}
+ size="small"
+ type="primary"
+ >
+ {t('tool.intervention.approveAndRemember')}
+ </Button>
+ <Dropdown
+ menu={{
+ items: [
+ {
+ disabled: approveLoading,
+ key: 'once',
+ label: t('tool.intervention.approveOnce'),
+ onClick: () => handleApprove(false),
+ },
+ ],
+ }}
+ >
+ <Button disabled={approveLoading} icon={ChevronDown} size="small" type="primary" />
+ </Dropdown>
+ </Space.Compact>
+ ) : (
+ <Button
+ loading={approveLoading}
+ onClick={() => handleApprove()}
+ size="small"
+ type="primary"
+ >
+ {t('tool.intervention.approve')}
+ </Button>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+export default ApprovalActions;
diff --git a/src/features/Conversation/Messages/Group/Tool/Render/Intervention/KeyValueEditor.tsx b/src/features/Conversation/Messages/Group/Tool/Render/Intervention/KeyValueEditor.tsx
new file mode 100644
index 00000000000..c26e2051dcf
--- /dev/null
+++ b/src/features/Conversation/Messages/Group/Tool/Render/Intervention/KeyValueEditor.tsx
@@ -0,0 +1,213 @@
+import { ActionIcon, Button, Icon, Input } from '@lobehub/ui';
+import { App, Form, FormInstance } from 'antd';
+import { createStyles } from 'antd-style';
+import { LucidePlus, LucideTrash } from 'lucide-react';
+import { memo, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+const useStyles = createStyles(({ css, token }) => ({
+ form: css`
+ position: relative;
+
+ width: 100%;
+ min-width: 600px;
+ padding: 8px;
+ border-radius: ${token.borderRadiusLG}px;
+ `,
+ formItem: css`
+ margin-block-end: 4px !important;
+ `,
+ input: css`
+ font-family: ${token.fontFamilyCode};
+ font-size: 12px;
+ `,
+ row: css`
+ position: relative;
+ `,
+ title: css`
+ margin-block-end: 4px;
+ color: ${token.colorTextTertiary};
+ `,
+}));
+
+interface KeyValueItem {
+ id: string;
+ key?: string;
+ value?: string;
+}
+
+interface KeyValueEditorProps {
+ initialValue?: Record<string, any>;
+ onCancel?: () => void;
+ onFinish?: (value: Record<string, any>) => Promise<void>;
+}
+
+const recordToFormList = (record: Record<string, any>): KeyValueItem[] =>
+ Object.entries(record)
+ .map(([key, val], index) => ({
+ id: `${key}-${index}`,
+ key,
+ value: typeof val === 'string' ? val : JSON.stringify(val),
+ }))
+ .filter((item) => item.key);
+
+const formListToRecord = (list: KeyValueItem[]): Record<string, any> => {
+ const record: Record<string, any> = {};
+ list.forEach((item) => {
+ if (item.key) {
+ try {
+ record[item.key] = JSON.parse(item.value || '""');
+ } catch {
+ record[item.key] = item.value || '';
+ }
+ }
+ });
+ return record;
+};
+
+const KeyValueEditor = memo<KeyValueEditorProps>(({ initialValue = {}, onFinish, onCancel }) => {
+ const { styles } = useStyles();
+ const { t } = useTranslation(['tool', 'common']);
+ const [form] = Form.useForm();
+ const { message } = App.useApp();
+ const formRef = useRef<FormInstance>(null);
+
+ useEffect(() => {
+ form.setFieldsValue({ items: recordToFormList(initialValue) });
+ }, [initialValue, form]);
+
+ const [updating, setUpdating] = useState(false);
+ const handleFinish = async () => {
+ setUpdating(true);
+ try {
+ await form.validateFields();
+ const values = form.getFieldsValue();
+ const record = formListToRecord(values.items || []);
+ await onFinish?.(record);
+ } catch (errorInfo) {
+ console.error('Validation Failed:', errorInfo);
+ message.error(t('updateArgs.formValidationFailed') || 'Please check the form for errors.');
+ }
+ setUpdating(false);
+ };
+
+ const handleCancel = () => {
+ onCancel?.();
+ };
+
+ const validateKeys = (_: any, item: KeyValueItem, items: KeyValueItem[]) => {
+ if (!item?.key) {
+ return Promise.resolve();
+ }
+ const keys = items.map((i) => i?.key).filter(Boolean);
+ if (keys.filter((k) => k === item.key).length > 1) {
+ return Promise.reject(new Error(t('updateArgs.duplicateKeyError')));
+ }
+
+ return Promise.resolve();
+ };
+
+ return (
+ <Form
+ autoComplete="off"
+ className={styles.form}
+ form={form}
+ initialValues={{ items: recordToFormList(initialValue) }}
+ ref={formRef}
+ >
+ <Flexbox className={styles.title} gap={8} horizontal>
+ <Flexbox flex={1}>key</Flexbox>
+ <Flexbox flex={4}>value</Flexbox>
+ </Flexbox>
+ <Form.List name="items">
+ {(fields, { add, remove }) => (
+ <Flexbox width={'100%'}>
+ {fields.map(({ key, name, ...restField }, index) => (
+ <Flexbox
+ align="center"
+ className={styles.row}
+ gap={8}
+ horizontal
+ key={key}
+ width={'100%'}
+ >
+ <Form.Item
+ {...restField}
+ className={styles.formItem}
+ name={[name, 'key']}
+ rules={[
+ { message: t('updateArgs.keyRequired'), required: true },
+ {
+ validator: (rule) =>
+ validateKeys(
+ rule,
+ form.getFieldValue(['items', index]),
+ form.getFieldValue('items'),
+ ),
+ },
+ ]}
+ style={{ flex: 1 }}
+ validateTrigger={['onChange', 'onBlur']}
+ >
+ <Input
+ allowClear
+ className={styles.input}
+ placeholder={t('updateArgs.form.key')}
+ variant={'filled'}
+ />
+ </Form.Item>
+ <Form.Item
+ {...restField}
+ className={styles.formItem}
+ name={[name, 'value']}
+ style={{ flex: 4 }}
+ >
+ <Input
+ allowClear
+ className={styles.input}
+ placeholder={t('updateArgs.form.value')}
+ variant={'filled'}
+ />
+ </Form.Item>
+ <ActionIcon
+ icon={LucideTrash}
+ onClick={() => remove(name)}
+ size={'small'}
+ style={{
+ marginBottom: 6,
+ }}
+ title={t('delete', { ns: 'common' })}
+ />
+ </Flexbox>
+ ))}
+ <Form.Item style={{ marginBottom: 0, marginTop: 8 }}>
+ <Flexbox gap={8} horizontal justify={'space-between'}>
+ <Button
+ color={'default'}
+ icon={<Icon icon={LucidePlus} />}
+ onClick={() => add({ id: `new-${Date.now()}`, key: '', value: '' })}
+ size={'small'}
+ variant="filled"
+ >
+ {t('updateArgs.form.add')}
+ </Button>
+
+ <Flexbox gap={8} horizontal>
+ <Button onClick={handleCancel} size={'small'}>
+ {t('cancel', { ns: 'common' })}
+ </Button>
+ <Button loading={updating} onClick={handleFinish} size={'small'} type={'primary'}>
+ {t('save', { ns: 'common' })}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ </Form.Item>
+ </Flexbox>
+ )}
+ </Form.List>
+ </Form>
+ );
+});
+
+export default KeyValueEditor;
diff --git a/src/features/Conversation/Messages/Group/Tool/Render/Intervention/ModeSelector.tsx b/src/features/Conversation/Messages/Group/Tool/Render/Intervention/ModeSelector.tsx
new file mode 100644
index 00000000000..8d4397e3e82
--- /dev/null
+++ b/src/features/Conversation/Messages/Group/Tool/Render/Intervention/ModeSelector.tsx
@@ -0,0 +1,134 @@
+import { Button, Dropdown, Icon, type MenuProps } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { ChevronDown, Hand, ListChecks, Zap } from 'lucide-react';
+import { memo, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Center } from 'react-layout-kit';
+
+import { useUserStore } from '@/store/user';
+
+import { ApprovalMode } from './index';
+
+const useStyles = createStyles(({ css, token }) => ({
+ icon: css`
+ border: 1px solid ${token.colorFillTertiary};
+ border-radius: ${token.borderRadius}px;
+ background: ${token.colorBgElevated};
+ `,
+ modeButton: css`
+ font-size: ${token.fontSizeSM}px;
+ color: ${token.colorTextSecondary};
+ `,
+ modeDesc: css`
+ margin-block-start: 2px;
+ font-size: 12px;
+ line-height: 1.4;
+ color: ${token.colorTextDescription};
+ `,
+ modeItem: css`
+ min-width: 160px;
+ `,
+ modeLabel: css`
+ font-size: ${token.fontSize}px;
+ font-weight: 500;
+ line-height: 1.4;
+ color: ${token.colorText};
+ `,
+}));
+
+const ModeSelector = memo(() => {
+ const { t } = useTranslation('chat');
+ const { styles } = useStyles();
+ const [approvalMode, setSettings] = useUserStore((s) => [
+ s.settings.tool?.approvalMode || 'manual',
+ s.setSettings,
+ ]);
+
+ const modeLabels = useMemo(
+ () => ({
+ 'allow-list': t('tool.intervention.mode.allowList'),
+ 'auto-run': t('tool.intervention.mode.autoRun'),
+ 'manual': t('tool.intervention.mode.manual'),
+ }),
+ [t],
+ );
+
+ const handleModeChange = useCallback(
+ async (mode: ApprovalMode) => {
+ await setSettings({ tool: { approvalMode: mode } });
+ },
+ [setSettings],
+ );
+
+ const menuItems = useMemo<MenuProps['items']>(
+ () => [
+ {
+ icon: (
+ <Center className={styles.icon} height={32} width={32}>
+ <Icon icon={Zap} />
+ </Center>
+ ),
+ key: 'auto-run',
+ label: (
+ <div className={styles.modeItem}>
+ <div className={styles.modeLabel}>{modeLabels['auto-run']}</div>
+ <div className={styles.modeDesc}>{t('tool.intervention.mode.autoRunDesc')}</div>
+ </div>
+ ),
+ onClick: () => handleModeChange('auto-run'),
+ },
+ {
+ icon: (
+ <Center className={styles.icon} height={32} width={32}>
+ <Icon icon={ListChecks} />
+ </Center>
+ ),
+ key: 'allow-list',
+ label: (
+ <div className={styles.modeItem}>
+ <div className={styles.modeLabel}>{modeLabels['allow-list']}</div>
+ <div className={styles.modeDesc}>{t('tool.intervention.mode.allowListDesc')}</div>
+ </div>
+ ),
+ onClick: () => handleModeChange('allow-list'),
+ },
+ {
+ icon: (
+ <Center className={styles.icon} height={32} width={32}>
+ <Icon icon={Hand} />
+ </Center>
+ ),
+ key: 'manual',
+ label: (
+ <div className={styles.modeItem}>
+ <div className={styles.modeLabel}>{modeLabels.manual}</div>
+ <div className={styles.modeDesc}>{t('tool.intervention.mode.manualDesc')}</div>
+ </div>
+ ),
+ onClick: () => handleModeChange('manual'),
+ },
+ ],
+ [modeLabels, handleModeChange, styles, t],
+ );
+
+ return (
+ <Dropdown
+ // @ts-expect-error activeKey 没在 Dropdown key 里很奇怪
+ menu={{ activeKey: approvalMode, items: menuItems }}
+ placement="bottomLeft"
+ >
+ <Button
+ className={styles.modeButton}
+ color={'default'}
+ icon={ChevronDown}
+ iconPosition="end"
+ size="small"
+ variant={'text'}
+ >
+ {modeLabels[approvalMode]}
+ </Button>
+ </Dropdown>
+ );
+});
+
+export default ModeSelector;
diff --git a/src/features/Conversation/Messages/Group/Tool/Render/Intervention/index.tsx b/src/features/Conversation/Messages/Group/Tool/Render/Intervention/index.tsx
new file mode 100644
index 00000000000..42e628ee653
--- /dev/null
+++ b/src/features/Conversation/Messages/Group/Tool/Render/Intervention/index.tsx
@@ -0,0 +1,99 @@
+import { safeParseJSON } from '@lobechat/utils';
+import { ActionIcon } from '@lobehub/ui';
+import { Edit3Icon } from 'lucide-react';
+import { Suspense, memo, useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useChatStore } from '@/store/chat';
+import { useUserStore } from '@/store/user';
+
+import Arguments from '../Arguments';
+import ApprovalActions from './ApprovalActions';
+import KeyValueEditor from './KeyValueEditor';
+import ModeSelector from './ModeSelector';
+
+export type ApprovalMode = 'auto-run' | 'allow-list' | 'manual';
+
+interface InterventionProps {
+ apiName: string;
+ id: string;
+ identifier: string;
+ requestArgs: string;
+ toolCallId: string;
+}
+
+const Intervention = memo<InterventionProps>(
+ ({ requestArgs, id, identifier, apiName, toolCallId }) => {
+ const { t } = useTranslation('chat');
+ const approvalMode = useUserStore((s) => s.settings.tool?.approvalMode || 'manual');
+ const [isEditing, setIsEditing] = useState(false);
+ const [optimisticUpdatePluginArguments] = useChatStore((s) => [
+ s.optimisticUpdatePluginArguments,
+ ]);
+
+ const handleCancel = useCallback(() => {
+ setIsEditing(false);
+ }, []);
+
+ const handleFinish = useCallback(
+ async (editedObject: Record<string, any>) => {
+ if (!id) return;
+
+ try {
+ const newArgsString = JSON.stringify(editedObject, null, 2);
+
+ if (newArgsString !== requestArgs) {
+ await optimisticUpdatePluginArguments(id, editedObject, true);
+ }
+ setIsEditing(false);
+ } catch (error) {
+ console.error('Error stringifying arguments:', error);
+ }
+ },
+ [requestArgs, id],
+ );
+
+ if (isEditing)
+ return (
+ <Suspense fallback={<Arguments arguments={requestArgs} />}>
+ <KeyValueEditor
+ initialValue={safeParseJSON(requestArgs || '')}
+ onCancel={handleCancel}
+ onFinish={handleFinish}
+ />
+ </Suspense>
+ );
+
+ return (
+ <Flexbox gap={12}>
+ <Arguments
+ actions={
+ <ActionIcon
+ icon={Edit3Icon}
+ onClick={() => {
+ setIsEditing(true);
+ }}
+ size={'small'}
+ title={t('edit', { ns: 'common' })}
+ />
+ }
+ arguments={requestArgs}
+ />
+
+ <Flexbox horizontal justify={'space-between'}>
+ <ModeSelector />
+ <ApprovalActions
+ apiName={apiName}
+ approvalMode={approvalMode}
+ identifier={identifier}
+ messageId={id}
+ toolCallId={toolCallId}
+ />
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+export default Intervention;
diff --git a/src/features/Conversation/Messages/Group/Tool/Render/RejectedResponse.tsx b/src/features/Conversation/Messages/Group/Tool/Render/RejectedResponse.tsx
new file mode 100644
index 00000000000..d0d8dfbe579
--- /dev/null
+++ b/src/features/Conversation/Messages/Group/Tool/Render/RejectedResponse.tsx
@@ -0,0 +1,45 @@
+import { Icon } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { AlertTriangle } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+const useStyles = createStyles(({ css, token }) => ({
+ container: css`
+ padding-block: 8px;
+ padding-inline: 6px;
+ `,
+ reason: css`
+ font-size: 12px;
+ color: ${token.colorTextTertiary};
+ `,
+ title: css`
+ font-size: 14px;
+ color: ${token.colorTextSecondary};
+ `,
+}));
+
+interface RejectedResponseProps {
+ reason?: string;
+}
+
+const RejectedResponse = memo<RejectedResponseProps>(({ reason }) => {
+ const { t } = useTranslation('chat');
+ const { styles, theme } = useStyles();
+
+ return (
+ <Flexbox className={styles.container} gap={8}>
+ <Flexbox align={'center'} gap={8} horizontal>
+ <Icon color={theme.colorWarning} icon={AlertTriangle} size={16} />
+ <div className={styles.title}>
+ {reason
+ ? t('tool.intervention.rejectedWithReason', { reason })
+ : t('tool.intervention.toolRejected')}
+ </div>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+export default RejectedResponse;
diff --git a/src/features/Conversation/Messages/Group/Tool/Render/index.tsx b/src/features/Conversation/Messages/Group/Tool/Render/index.tsx
index 1cd790185b3..7e0061b977d 100644
--- a/src/features/Conversation/Messages/Group/Tool/Render/index.tsx
+++ b/src/features/Conversation/Messages/Group/Tool/Render/index.tsx
@@ -1,15 +1,18 @@
import { LOADING_FLAT } from '@lobechat/const';
-import { ChatToolResult } from '@lobechat/types';
+import { ChatToolResult, ToolIntervention } from '@lobechat/types';
import { Suspense, memo } from 'react';
import CustomRender from './CustomRender';
import ErrorResponse from './ErrorResponse';
+import Intervention from './Intervention';
import LoadingPlaceholder from './LoadingPlaceholder';
+import RejectedResponse from './RejectedResponse';
interface RenderProps {
apiName: string;
arguments?: string;
identifier: string;
+ intervention?: ToolIntervention;
/**
* ContentBlock ID (not the group message ID)
*/
@@ -18,6 +21,7 @@ interface RenderProps {
setShowPluginRender: (show: boolean) => void;
showPluginRender: boolean;
toolCallId: string;
+ toolMessageId?: string;
type?: string;
}
@@ -38,7 +42,25 @@ const Render = memo<RenderProps>(
apiName,
result,
type,
+ intervention,
+ toolMessageId,
}) => {
+ if (toolMessageId && intervention?.status === 'pending') {
+ return (
+ <Intervention
+ apiName={apiName}
+ id={toolMessageId}
+ identifier={identifier}
+ requestArgs={requestArgs || ''}
+ toolCallId={toolCallId}
+ />
+ );
+ }
+
+ if (intervention?.status === 'rejected') {
+ return <RejectedResponse reason={intervention.rejectedReason} />;
+ }
+
if (!result) return null;
// Handle error state
diff --git a/src/features/Conversation/Messages/Group/Tool/index.tsx b/src/features/Conversation/Messages/Group/Tool/index.tsx
index ce2b7ed3d9e..edf3a24c815 100644
--- a/src/features/Conversation/Messages/Group/Tool/index.tsx
+++ b/src/features/Conversation/Messages/Group/Tool/index.tsx
@@ -1,5 +1,5 @@
-import { ChatToolResult } from '@lobechat/types';
-import { CSSProperties, memo, useState } from 'react';
+import { ChatToolResult, ToolIntervention } from '@lobechat/types';
+import { CSSProperties, memo, useEffect, useState } from 'react';
import { Flexbox } from 'react-layout-kit';
import AnimatedCollapsed from '@/components/AnimatedCollapsed';
@@ -10,15 +10,17 @@ import Render from './Render';
export interface GroupToolProps {
apiName: string;
arguments?: string;
- id: string;
- identifier: string;
- index: number;
/**
* ContentBlock ID (not the group message ID)
*/
- messageId: string;
+ assistantMessageId: string;
+ id: string;
+ identifier: string;
+ index: number;
+ intervention?: ToolIntervention;
result?: ChatToolResult;
style?: CSSProperties;
+ toolMessageId?: string;
type?: string;
}
@@ -29,10 +31,29 @@ export interface GroupToolProps {
* so we always show the results directly.
*/
const Tool = memo<GroupToolProps>(
- ({ arguments: requestArgs, apiName, messageId, id, index, identifier, style, result, type }) => {
+ ({
+ arguments: requestArgs,
+ apiName,
+ assistantMessageId,
+ id,
+ intervention,
+ index,
+ identifier,
+ style,
+ result,
+ type,
+ toolMessageId,
+ }) => {
// Default to false since group messages are all completed
- const [showDetail, setShowDetail] = useState(false);
- const [showPluginRender, setShowPluginRender] = useState(false);
+
+ const [showToolContent, setShowToolDetail] = useState(false);
+ const [showCustomPluginUI, setShowCustomPluginUI] = useState(false);
+
+ useEffect(() => {
+ if (intervention?.status === 'pending') {
+ setShowToolDetail(true);
+ }
+ }, [intervention?.status]);
return (
<Flexbox gap={8} style={style}>
@@ -42,24 +63,27 @@ const Tool = memo<GroupToolProps>(
id={id}
identifier={identifier}
index={index}
- messageId={messageId}
+ intervention={intervention}
+ messageId={assistantMessageId}
result={result}
- setShowPluginRender={setShowPluginRender}
- setShowRender={setShowDetail}
- showPluginRender={showPluginRender}
- showRender={showDetail}
+ setShowPluginRender={setShowCustomPluginUI}
+ setShowRender={setShowToolDetail}
+ showPluginRender={showCustomPluginUI}
+ showRender={showToolContent}
type={type}
/>
- <AnimatedCollapsed open={showDetail} width={{ collapsed: 'auto' }}>
+ <AnimatedCollapsed open={showToolContent} width={{ collapsed: 'auto' }}>
<Render
apiName={apiName}
arguments={requestArgs}
identifier={identifier}
- messageId={messageId}
+ intervention={intervention}
+ messageId={assistantMessageId}
result={result}
- setShowPluginRender={setShowPluginRender}
- showPluginRender={showPluginRender}
+ setShowPluginRender={setShowCustomPluginUI}
+ showPluginRender={showCustomPluginUI}
toolCallId={id}
+ toolMessageId={toolMessageId}
type={type}
/>
</AnimatedCollapsed>
diff --git a/src/features/Conversation/Messages/Group/Tools.tsx b/src/features/Conversation/Messages/Group/Tools.tsx
index fa5106da8cc..ecc0ae55ee9 100644
--- a/src/features/Conversation/Messages/Group/Tools.tsx
+++ b/src/features/Conversation/Messages/Group/Tools.tsx
@@ -32,12 +32,14 @@ export const Tools = memo<ToolsRendererProps>(({ messageId, tools }) => {
<Tool
apiName={tool.apiName}
arguments={tool.arguments}
+ assistantMessageId={messageId}
id={tool.id}
identifier={tool.identifier}
index={index}
+ intervention={tool.intervention}
key={tool.id}
- messageId={messageId}
result={tool.result}
+ toolMessageId={tool.result_msg_id}
type={tool.type}
/>
))}
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index f2212c63a52..da528c8105b 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -398,6 +398,26 @@ export default {
remained: '剩余',
used: '使用',
},
+ tool: {
+ intervention: {
+ approve: '批准',
+ approveAndRemember: '批准并记住',
+ approveOnce: '仅本次批准',
+ mode: {
+ allowList: '白名单',
+ allowListDesc: '仅自动执行已批准的工具',
+ autoRun: '自动批准',
+ autoRunDesc: '自动批准所有工具执行',
+ manual: '手动',
+ manualDesc: '每次调用都需要手动批准',
+ },
+ reject: '拒绝',
+ rejectReasonPlaceholder: '输入拒绝原因将帮助 Agent 理解并优化后续行动',
+ rejectTitle: '拒绝本次工具调用',
+ rejectedWithReason: '本次工具调用被主动拒绝:{{reason}}',
+ toolRejected: '本次工具调用被主动拒绝',
+ },
+ },
topic: {
checkOpenNewTopic: '是否开启新话题?',
checkSaveCurrentMessages: '是否保存当前会话为话题?',
diff --git a/src/locales/default/common.ts b/src/locales/default/common.ts
index 33130e28cc9..83d279eefb2 100644
--- a/src/locales/default/common.ts
+++ b/src/locales/default/common.ts
@@ -138,6 +138,7 @@ export default {
},
},
close: '关闭',
+ confirm: '确认',
contact: '联系我们',
copy: '复制',
copyFail: '复制失败',
diff --git a/src/server/routers/lambda/message.ts b/src/server/routers/lambda/message.ts
index daf28795746..b29448c1c9f 100644
--- a/src/server/routers/lambda/message.ts
+++ b/src/server/routers/lambda/message.ts
@@ -179,11 +179,14 @@ export const messageRouter = router({
.input(
z.object({
id: z.string(),
+ sessionId: z.string().nullable().optional(),
+ topicId: z.string().nullable().optional(),
value: UpdateMessagePluginSchema.partial(),
}),
)
.mutation(async ({ input, ctx }) => {
- return ctx.messageModel.updateMessagePlugin(input.id, input.value);
+ const { id, value, ...options } = input;
+ return ctx.messageService.updateMessagePlugin(id, value, options);
}),
updateMessageRAG: messageProcedure
diff --git a/src/server/services/message/index.ts b/src/server/services/message/index.ts
index be2f80d5b26..f81207e7a70 100644
--- a/src/server/services/message/index.ts
+++ b/src/server/services/message/index.ts
@@ -150,6 +150,19 @@ export class MessageService {
return this.queryWithSuccess(options);
}
+ /**
+ * Update message plugin and return message list
+ * Pattern: update + conditional query
+ */
+ async updateMessagePlugin(
+ id: string,
+ value: any,
+ options: QueryOptions,
+ ): Promise<{ messages?: UIChatMessage[], success: boolean; }> {
+ await this.messageModel.updateMessagePlugin(id, value);
+ return this.queryWithSuccess(options);
+ }
+
/**
* Update message and return message list
* Pattern: update + conditional query
diff --git a/src/services/message/index.ts b/src/services/message/index.ts
index 9dafa48ede5..6f3efd149cd 100644
--- a/src/services/message/index.ts
+++ b/src/services/message/index.ts
@@ -6,6 +6,7 @@ import {
CreateMessageParams,
CreateMessageResult,
MessageMetadata,
+ MessagePluginItem,
ModelRankItem,
UIChatMessage,
UpdateMessageParams,
@@ -77,8 +78,9 @@ export class MessageService {
};
updateMessageError = async (id: string, value: ChatMessageError) => {
- const error = value.type ? value : { body: value, message: value.message, type: 'ApplicationRuntimeError' };
-
+ const error = value.type
+ ? value
+ : { body: value, message: value.message, type: 'ApplicationRuntimeError' };
return lambdaClient.message.update.mutate({ id, value: { error } });
};
@@ -153,6 +155,19 @@ export class MessageService {
});
};
+ updateMessagePlugin = async (
+ id: string,
+ value: Partial<Omit<MessagePluginItem, 'id'>>,
+ options?: { sessionId?: string | null; topicId?: string | null },
+ ): Promise<UpdateMessageResult> => {
+ return lambdaClient.message.updateMessagePlugin.mutate({
+ id,
+ sessionId: options?.sessionId,
+ topicId: options?.topicId,
+ value,
+ });
+ };
+
updateMessageRAG = async (
id: string,
data: UpdateMessageRAGParams,
diff --git a/src/store/chat/agents/GeneralChatAgent.ts b/src/store/chat/agents/GeneralChatAgent.ts
index 0f06581579f..e40bbf962cb 100644
--- a/src/store/chat/agents/GeneralChatAgent.ts
+++ b/src/store/chat/agents/GeneralChatAgent.ts
@@ -9,20 +9,22 @@ import {
GeneralAgentCallToolsBatchInstructionPayload,
GeneralAgentCallingToolInstructionPayload,
GeneralAgentConfig,
+ InterventionChecker,
} from '@lobechat/agent-runtime';
+import type { ChatToolPayload, HumanInterventionConfig } from '@lobechat/types';
/**
* ChatAgent - The "Brain" of the chat agent
*
* This agent implements a simple but powerful decision loop:
* 1. user_input → call_llm (with optional RAG/Search preprocessing)
- * 2. llm_result → check for tool_calls
- * - If has tool_calls → call_tools_batch (parallel execution)
- * - If no tool_calls → finish
+ * 2. llm_result → check for tool_calls and intervention requirements
+ * - Tools not requiring intervention → call_tools_batch (execute immediately)
+ * - Tools requiring intervention → request_human_approve (wait for approval)
+ * - Mixed (both types) → [call_tools_batch, request_human_approve] (execute safe ones first, then request approval)
+ * - No tool_calls → finish
* 3. tools_batch_result → call_llm (process tool results)
*
- * Note: RAG and Search workflow preprocessing are handled externally
- * before creating the agent runtime, keeping the agent logic simple.
*/
export class GeneralChatAgent implements Agent {
private config: GeneralAgentConfig;
@@ -31,6 +33,63 @@ export class GeneralChatAgent implements Agent {
this.config = config;
}
+ /**
+ * Get intervention configuration for a specific tool call
+ */
+ private getToolInterventionConfig(
+ toolCalling: ChatToolPayload,
+ state: AgentState,
+ ): HumanInterventionConfig | undefined {
+ const { identifier, apiName } = toolCalling;
+ const manifest = state.toolManifestMap[identifier];
+
+ if (!manifest) return undefined;
+
+ // Find the specific API in the manifest
+ const api = manifest.api?.find((a: any) => a.name === apiName);
+
+ // API-level config takes precedence over tool-level config
+ return api?.humanIntervention ?? manifest.humanIntervention;
+ }
+
+ /**
+ * Check if tool calls need human intervention
+ * Returns [toolsNeedingIntervention, toolsToExecute]
+ */
+ private checkInterventionNeeded(
+ toolsCalling: ChatToolPayload[],
+ state: AgentState,
+ ): [ChatToolPayload[], ChatToolPayload[]] {
+ const toolsNeedingIntervention: ChatToolPayload[] = [];
+ const toolsToExecute: ChatToolPayload[] = [];
+
+ for (const toolCalling of toolsCalling) {
+ const config = this.getToolInterventionConfig(toolCalling, state);
+
+ // Parse arguments for intervention checking
+ let toolArgs: Record<string, any> = {};
+ try {
+ toolArgs = JSON.parse(toolCalling.arguments || '{}');
+ } catch {
+ // Invalid JSON, treat as empty args
+ }
+
+ const policy = InterventionChecker.shouldIntervene({
+ config,
+ toolArgs,
+ });
+
+ if (policy === 'never') {
+ toolsToExecute.push(toolCalling);
+ } else {
+ // 'require' or 'first' (when not confirmed) requires intervention
+ toolsNeedingIntervention.push(toolCalling);
+ }
+ }
+
+ return [toolsNeedingIntervention, toolsToExecute];
+ }
+
async runner(
context: AgentRuntimeContext,
state: AgentState,
@@ -55,26 +114,47 @@ export class GeneralChatAgent implements Agent {
context.payload as GeneralAgentCallLLMResultPayload;
if (hasToolsCalling && toolsCalling && toolsCalling.length > 0) {
- // No intervention needed, proceed with tool execution
- // Use batch execution for multiple tool calls to improve performance
- if (toolsCalling.length > 1) {
- return {
- payload: {
- parentMessageId,
- toolsCalling,
- } as GeneralAgentCallToolsBatchInstructionPayload,
- type: 'call_tools_batch',
- };
- } else if (toolsCalling.length === 1) {
- // Single tool executes directly
- return {
- payload: {
- parentMessageId,
- toolCalling: toolsCalling[0],
- } as GeneralAgentCallingToolInstructionPayload,
- type: 'call_tool',
- };
+ // Check which tools need human intervention
+ const [toolsNeedingIntervention, toolsToExecute] = this.checkInterventionNeeded(
+ toolsCalling,
+ state,
+ );
+
+ const instructions: AgentInstruction[] = [];
+
+ // Execute tools that don't need intervention first
+ // These will run immediately before any approval requests
+ if (toolsToExecute.length > 0) {
+ if (toolsToExecute.length > 1) {
+ instructions.push({
+ payload: {
+ parentMessageId,
+ toolsCalling: toolsToExecute,
+ } as GeneralAgentCallToolsBatchInstructionPayload,
+ type: 'call_tools_batch',
+ });
+ } else {
+ instructions.push({
+ payload: {
+ parentMessageId,
+ toolCalling: toolsToExecute[0],
+ } as GeneralAgentCallingToolInstructionPayload,
+ type: 'call_tool',
+ });
+ }
+ }
+
+ // Request approval for tools that need intervention
+ // Runtime will execute this after safe tools and pause with status='waiting_for_human'
+ if (toolsNeedingIntervention.length > 0) {
+ instructions.push({
+ pendingToolsCalling: toolsNeedingIntervention,
+ reason: 'human_intervention_required',
+ type: 'request_human_approve',
+ });
}
+
+ return instructions;
}
// No tool calls, conversation is complete
@@ -88,6 +168,24 @@ export class GeneralChatAgent implements Agent {
case 'tool_result': {
const { parentMessageId } = context.payload as GeneralAgentCallToolResultPayload;
+ // Check if there are still pending tool messages waiting for approval
+ const pendingToolMessages = state.messages.filter(
+ (m: any) => m.role === 'tool' && m.pluginIntervention?.status === 'pending',
+ );
+
+ // If there are pending tools, wait for human approval
+ if (pendingToolMessages.length > 0) {
+ const pendingTools = pendingToolMessages.map((m: any) => m.plugin).filter(Boolean);
+
+ return {
+ pendingToolsCalling: pendingTools,
+ reason: 'Some tools still pending approval',
+ skipCreateToolMessage: true,
+ type: 'request_human_approve',
+ };
+ }
+
+ // No pending tools, continue to call LLM with tool results
return {
payload: {
messages: state.messages,
@@ -102,6 +200,25 @@ export class GeneralChatAgent implements Agent {
case 'tools_batch_result': {
const { parentMessageId } = context.payload as GeneralAgentCallToolResultPayload;
+
+ // Check if there are still pending tool messages waiting for approval
+ const pendingToolMessages = state.messages.filter(
+ (m: any) => m.role === 'tool' && m.pluginIntervention?.status === 'pending',
+ );
+
+ // If there are pending tools, wait for human approval
+ if (pendingToolMessages.length > 0) {
+ const pendingTools = pendingToolMessages.map((m: any) => m.plugin).filter(Boolean);
+
+ return {
+ pendingToolsCalling: pendingTools,
+ reason: 'Some tools still pending approval',
+ skipCreateToolMessage: true,
+ type: 'request_human_approve',
+ };
+ }
+
+ // No pending tools, continue to call LLM with tool results
return {
payload: {
messages: state.messages,
diff --git a/src/store/chat/agents/__tests__/GeneralChatAgent.test.ts b/src/store/chat/agents/__tests__/GeneralChatAgent.test.ts
new file mode 100644
index 00000000000..05792da67a5
--- /dev/null
+++ b/src/store/chat/agents/__tests__/GeneralChatAgent.test.ts
@@ -0,0 +1,605 @@
+import { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';
+import { ChatToolPayload } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { GeneralChatAgent } from '../GeneralChatAgent';
+
+describe('GeneralChatAgent', () => {
+ const mockModelRuntimeConfig = {
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ };
+
+ const createMockState = (overrides?: Partial<AgentState>): AgentState => ({
+ sessionId: 'test-session',
+ status: 'running',
+ messages: [],
+ toolManifestMap: {},
+ stepCount: 0,
+ usage: {
+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },
+ tools: { totalCalls: 0, totalTimeMs: 0, byTool: [] },
+ humanInteraction: {
+ approvalRequests: 0,
+ promptRequests: 0,
+ selectRequests: 0,
+ totalWaitingTimeMs: 0,
+ },
+ },
+ cost: {
+ calculatedAt: new Date().toISOString(),
+ currency: 'USD',
+ llm: { byModel: [], currency: 'USD', total: 0 },
+ tools: { byTool: [], currency: 'USD', total: 0 },
+ total: 0,
+ },
+ createdAt: new Date().toISOString(),
+ lastModified: new Date().toISOString(),
+ ...overrides,
+ });
+
+ const createMockContext = (
+ phase: AgentRuntimeContext['phase'],
+ payload?: any,
+ ): AgentRuntimeContext => ({
+ phase,
+ payload,
+ session: {
+ sessionId: 'test-session',
+ messageCount: 0,
+ status: 'running',
+ stepCount: 0,
+ },
+ });
+
+ describe('init and user_input phase', () => {
+ it('should return call_llm instruction for init phase', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ sessionId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = createMockState({
+ messages: [{ role: 'user', content: 'Hello' }] as any,
+ });
+ const context = createMockContext('init', { model: 'gpt-4o-mini', provider: 'openai' });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual({
+ type: 'call_llm',
+ payload: {
+ messages: state.messages,
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ },
+ });
+ });
+
+ it('should return call_llm instruction for user_input phase', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ sessionId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = createMockState({
+ messages: [{ role: 'user', content: 'What is the weather?' }] as any,
+ });
+ const context = createMockContext('user_input', {
+ message: { role: 'user', content: 'What is the weather?' },
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual({
+ type: 'call_llm',
+ payload: {
+ messages: state.messages,
+ message: { role: 'user', content: 'What is the weather?' },
+ },
+ });
+ });
+ });
+
+ describe('llm_result phase', () => {
+ it('should return finish when no tool calls', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ sessionId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = createMockState();
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: false,
+ toolsCalling: [],
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual({
+ type: 'finish',
+ reason: 'completed',
+ reasonDetail: 'LLM response completed without tool calls',
+ });
+ });
+
+ it('should return call_tool for single tool that does not need intervention', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ sessionId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const toolCall: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'test-plugin',
+ apiName: 'test-api',
+ arguments: '{}',
+ type: 'default',
+ };
+
+ const state = createMockState({
+ toolManifestMap: {
+ 'test-plugin': {
+ identifier: 'test-plugin',
+ // No humanIntervention config = no intervention needed
+ },
+ },
+ });
+
+ 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 return call_tools_batch for multiple tools that do not need intervention', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ sessionId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const toolCalls: ChatToolPayload[] = [
+ {
+ id: 'call-1',
+ identifier: 'plugin-1',
+ apiName: 'api-1',
+ arguments: '{}',
+ type: 'default',
+ },
+ {
+ id: 'call-2',
+ identifier: 'plugin-2',
+ apiName: 'api-2',
+ arguments: '{}',
+ type: 'default',
+ },
+ ];
+
+ const state = createMockState({
+ toolManifestMap: {
+ 'plugin-1': { identifier: 'plugin-1' },
+ 'plugin-2': { identifier: 'plugin-2' },
+ },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: toolCalls,
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual([
+ {
+ type: 'call_tools_batch',
+ payload: {
+ parentMessageId: 'msg-1',
+ toolsCalling: toolCalls,
+ },
+ },
+ ]);
+ });
+
+ it('should return request_human_approve for tools requiring intervention', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ sessionId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const toolCall: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'dangerous-plugin',
+ apiName: 'delete-api',
+ arguments: '{}',
+ type: 'default',
+ };
+
+ const state = createMockState({
+ toolManifestMap: {
+ 'dangerous-plugin': {
+ identifier: 'dangerous-plugin',
+ humanIntervention: 'require', // Always require approval
+ },
+ },
+ });
+
+ 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 return both call_tools_batch and request_human_approve for mixed tools', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ sessionId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const safeTool: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'safe-plugin',
+ apiName: 'read-api',
+ arguments: '{}',
+ type: 'default',
+ };
+
+ const dangerousTool: ChatToolPayload = {
+ id: 'call-2',
+ identifier: 'dangerous-plugin',
+ apiName: 'delete-api',
+ arguments: '{}',
+ type: 'default',
+ };
+
+ const state = createMockState({
+ toolManifestMap: {
+ 'safe-plugin': {
+ identifier: 'safe-plugin',
+ // No intervention
+ },
+ 'dangerous-plugin': {
+ identifier: 'dangerous-plugin',
+ humanIntervention: 'require',
+ },
+ },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [safeTool, dangerousTool],
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual([
+ {
+ type: 'call_tool',
+ payload: {
+ parentMessageId: 'msg-1',
+ toolCalling: safeTool,
+ },
+ },
+ {
+ type: 'request_human_approve',
+ pendingToolsCalling: [dangerousTool],
+ reason: 'human_intervention_required',
+ },
+ ]);
+ });
+ });
+
+ describe('tool_result phase', () => {
+ it('should return call_llm when no pending tools', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ sessionId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = createMockState({
+ messages: [
+ { role: 'user', content: 'Hello' },
+ { role: 'assistant', content: '', tools: [] },
+ { role: 'tool', content: 'Result', tool_call_id: 'call-1' },
+ ] as any,
+ });
+
+ const context = createMockContext('tool_result', {
+ parentMessageId: 'tool-msg-1',
+ result: { data: 'result' },
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual({
+ type: 'call_llm',
+ payload: {
+ messages: state.messages,
+ model: 'gpt-4o-mini',
+ parentMessageId: 'tool-msg-1',
+ provider: 'openai',
+ tools: undefined,
+ },
+ });
+ });
+
+ it('should return request_human_approve when there are pending tools', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ sessionId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const pendingPlugin: ChatToolPayload = {
+ id: 'call-2',
+ identifier: 'plugin-2',
+ apiName: 'api-2',
+ arguments: '{}',
+ type: 'default',
+ };
+
+ const state = createMockState({
+ messages: [
+ { role: 'user', content: 'Hello' },
+ { role: 'assistant', content: '', tools: [] },
+ { role: 'tool', content: 'Result', tool_call_id: 'call-1' },
+ {
+ role: 'tool',
+ content: '',
+ tool_call_id: 'call-2',
+ plugin: pendingPlugin,
+ pluginIntervention: { status: 'pending' },
+ },
+ ] as any,
+ });
+
+ const context = createMockContext('tool_result', {
+ parentMessageId: 'tool-msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual({
+ type: 'request_human_approve',
+ pendingToolsCalling: [pendingPlugin],
+ reason: 'Some tools still pending approval',
+ skipCreateToolMessage: true,
+ });
+ });
+ });
+
+ describe('tools_batch_result phase', () => {
+ it('should return call_llm when no pending tools', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ sessionId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = createMockState({
+ messages: [
+ { role: 'user', content: 'Hello' },
+ { role: 'assistant', content: '', tools: [] },
+ { role: 'tool', content: 'Result 1', tool_call_id: 'call-1' },
+ { role: 'tool', content: 'Result 2', tool_call_id: 'call-2' },
+ ] as any,
+ });
+
+ const context = createMockContext('tools_batch_result', {
+ parentMessageId: 'tool-msg-2',
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual({
+ type: 'call_llm',
+ payload: {
+ messages: state.messages,
+ model: 'gpt-4o-mini',
+ parentMessageId: 'tool-msg-2',
+ provider: 'openai',
+ tools: undefined,
+ },
+ });
+ });
+
+ it('should return request_human_approve when there are pending tools', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ sessionId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const pendingPlugin: ChatToolPayload = {
+ id: 'call-3',
+ identifier: 'plugin-3',
+ apiName: 'api-3',
+ arguments: '{}',
+ type: 'default',
+ };
+
+ const state = createMockState({
+ messages: [
+ { role: 'user', content: 'Hello' },
+ { role: 'assistant', content: '', tools: [] },
+ { role: 'tool', content: 'Result 1', tool_call_id: 'call-1' },
+ { role: 'tool', content: 'Result 2', tool_call_id: 'call-2' },
+ {
+ role: 'tool',
+ content: '',
+ tool_call_id: 'call-3',
+ plugin: pendingPlugin,
+ pluginIntervention: { status: 'pending' },
+ },
+ ] as any,
+ });
+
+ const context = createMockContext('tools_batch_result', {
+ parentMessageId: 'tool-msg-2',
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual({
+ type: 'request_human_approve',
+ pendingToolsCalling: [pendingPlugin],
+ reason: 'Some tools still pending approval',
+ skipCreateToolMessage: true,
+ });
+ });
+ });
+
+ describe('error phase', () => {
+ it('should return finish instruction with error details', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ sessionId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = createMockState();
+ const errorMessage = 'Network timeout';
+ const context = createMockContext('error', {
+ error: new Error(errorMessage),
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual({
+ type: 'finish',
+ reason: 'error_recovery',
+ reasonDetail: errorMessage,
+ });
+ });
+
+ it('should handle error without message', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ sessionId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = createMockState();
+ const context = createMockContext('error', { error: {} });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual({
+ type: 'finish',
+ reason: 'error_recovery',
+ reasonDetail: 'Unknown error occurred',
+ });
+ });
+ });
+
+ describe('unknown phase', () => {
+ it('should return finish instruction for unknown phase', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ sessionId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = createMockState();
+ const context = createMockContext('unknown_phase' as any);
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual({
+ type: 'finish',
+ reason: 'agent_decision',
+ reasonDetail: 'Unknown phase: unknown_phase',
+ });
+ });
+ });
+
+ describe('intervention checking', () => {
+ it('should check intervention at API level when configured', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ sessionId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const toolCall: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'plugin',
+ apiName: 'dangerous-api',
+ arguments: '{}',
+ type: 'default',
+ };
+
+ const state = createMockState({
+ toolManifestMap: {
+ plugin: {
+ identifier: 'plugin',
+ // Tool-level config
+ humanIntervention: 'never',
+ api: [
+ {
+ name: 'safe-api',
+ // Safe API
+ },
+ {
+ name: 'dangerous-api',
+ // API-level config overrides tool-level
+ humanIntervention: 'require',
+ },
+ ],
+ },
+ },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ // Should require approval because API-level config overrides
+ expect(result).toEqual([
+ {
+ type: 'request_human_approve',
+ pendingToolsCalling: [toolCall],
+ reason: 'human_intervention_required',
+ },
+ ]);
+ });
+ });
+});
diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.ts
index ad913f196cb..0bcb7961067 100644
--- a/src/store/chat/agents/createAgentExecutors.ts
+++ b/src/store/chat/agents/createAgentExecutors.ts
@@ -13,6 +13,7 @@ import {
} from '@lobechat/agent-runtime';
import type { ChatToolPayload, CreateMessageParams } from '@lobechat/types';
import debug from 'debug';
+import pMap from 'p-map';
import type { ChatStore } from '@/store/chat/store';
@@ -43,6 +44,7 @@ export const createAgentExecutors = (context: {
}) => {
let shouldSkipCreateMessage = context.skipCreateFirstMessage;
+ /* eslint-disable sort-keys-fix/sort-keys-fix */
const executors: Partial<Record<AgentInstruction['type'], InstructionExecutor>> = {
/**
* Custom call_llm executor
@@ -239,39 +241,56 @@ export const createAgentExecutors = (context: {
// Find the last assistant message (should be created by call_llm)
const assistantMessage = latestMessages.findLast((m) => m.role === 'assistant');
- // Always create new tool message (following server-side pattern)
- // This ensures consistency and avoids duplicate execution
- log(
- '[%s][call_tool] Creating tool message for tool_call_id: %s',
- sessionLogId,
- chatToolPayload.id,
- );
+ let toolMessageId: string;
- const toolMessageParams: CreateMessageParams = {
- content: '',
- groupId: assistantMessage?.groupId,
- parentId: payload.parentMessageId,
- plugin: chatToolPayload,
- role: 'tool',
- sessionId: context.get().activeId,
- threadId: context.params.threadId,
- tool_call_id: chatToolPayload.id,
- topicId: context.get().activeTopicId,
- };
-
- const createResult = await context.get().optimisticCreateMessage(toolMessageParams);
+ if (payload.skipCreateToolMessage) {
+ // Reuse existing tool message (resumption mode)
+ toolMessageId = payload.parentMessageId;
+ // Check if tool message already exists (e.g., from human approval flow)
+ const existingToolMessage = latestMessages.find((m) => m.id === toolMessageId)!;
- if (!createResult) {
log(
- '[%s][call_tool] ERROR: Failed to create tool message for tool_call_id: %s',
+ '[%s][call_tool] Resuming with existing tool message: %s (status: %s)',
+ sessionLogId,
+ toolMessageId,
+ existingToolMessage.pluginIntervention?.status,
+ );
+ } else {
+ // Create new tool message (normal mode)
+ log(
+ '[%s][call_tool] Creating tool message for tool_call_id: %s',
sessionLogId,
chatToolPayload.id,
);
- throw new Error(`Failed to create tool message for tool_call_id: ${chatToolPayload.id}`);
- }
- const toolMessageId = createResult.id;
- log('[%s][call_tool] Created tool message, id: %s', sessionLogId, toolMessageId);
+ const toolMessageParams: CreateMessageParams = {
+ content: '',
+ groupId: assistantMessage?.groupId,
+ parentId: payload.parentMessageId,
+ plugin: chatToolPayload,
+ role: 'tool',
+ sessionId: context.get().activeId,
+ threadId: context.params.threadId,
+ tool_call_id: chatToolPayload.id,
+ topicId: context.get().activeTopicId,
+ };
+
+ const createResult = await context.get().optimisticCreateMessage(toolMessageParams);
+
+ if (!createResult) {
+ log(
+ '[%s][call_tool] ERROR: Failed to create tool message for tool_call_id: %s',
+ sessionLogId,
+ chatToolPayload.id,
+ );
+ throw new Error(
+ `Failed to create tool message for tool_call_id: ${chatToolPayload.id}`,
+ );
+ }
+
+ toolMessageId = createResult.id;
+ log('[%s][call_tool] Created tool message, id: %s', sessionLogId, toolMessageId);
+ }
// Execute tool
log('[%s][call_tool] Executing tool %s ...', sessionLogId, toolName);
@@ -371,6 +390,105 @@ export const createAgentExecutors = (context: {
}
},
+ /** Create human approve executor */
+ request_human_approve: async (instruction, state) => {
+ const { pendingToolsCalling, reason, skipCreateToolMessage } = instruction as Extract<
+ AgentInstruction,
+ { type: 'request_human_approve' }
+ >;
+ const newState = structuredClone(state);
+ const events: AgentEvent[] = [];
+ const sessionLogId = `${state.sessionId}:${state.stepCount}`;
+
+ log(
+ '[%s][request_human_approve] Executor start, pending tools count: %d, reason: %s',
+ sessionLogId,
+ pendingToolsCalling.length,
+ reason || 'human_intervention_required',
+ );
+
+ // Update state to waiting_for_human
+ newState.lastModified = new Date().toISOString();
+ newState.status = 'waiting_for_human';
+ newState.pendingToolsCalling = pendingToolsCalling;
+
+ // Get assistant message to extract groupId and parentId
+ const latestMessages = context.get().dbMessagesMap[context.messageKey] || [];
+ const assistantMessage = latestMessages.findLast((m) => m.role === 'assistant');
+
+ if (!assistantMessage) {
+ log('[%s][request_human_approve] ERROR: No assistant message found', sessionLogId);
+ throw new Error('No assistant message found for intervention');
+ }
+
+ log(
+ '[%s][request_human_approve] Found assistant message: %s',
+ sessionLogId,
+ assistantMessage.id,
+ );
+
+ if (skipCreateToolMessage) {
+ // Resumption mode: Tool messages already exist, just verify them
+ log('[%s][request_human_approve] Resuming with existing tool messages', sessionLogId);
+ } else {
+ // Create tool messages for each pending tool call with intervention status
+ await pMap(pendingToolsCalling, async (toolPayload) => {
+ const toolName = `${toolPayload.identifier}/${toolPayload.apiName}`;
+ log(
+ '[%s][request_human_approve] Creating tool message for %s with tool_call_id: %s',
+ sessionLogId,
+ toolName,
+ toolPayload.id,
+ );
+
+ const toolMessageParams: CreateMessageParams = {
+ content: '',
+ groupId: assistantMessage.groupId,
+ parentId: assistantMessage.id,
+ plugin: {
+ ...toolPayload,
+ },
+ pluginIntervention: { status: 'pending' },
+ role: 'tool',
+ sessionId: context.get().activeId,
+ threadId: context.params.threadId,
+ tool_call_id: toolPayload.id,
+ topicId: context.get().activeTopicId,
+ };
+
+ const createResult = await context.get().optimisticCreateMessage(toolMessageParams);
+
+ if (!createResult) {
+ log(
+ '[%s][request_human_approve] ERROR: Failed to create tool message for %s',
+ sessionLogId,
+ toolName,
+ );
+ throw new Error(`Failed to create tool message for ${toolName}`);
+ }
+
+ log(
+ '[%s][request_human_approve] Created tool message: %s for %s',
+ sessionLogId,
+ createResult.id,
+ toolName,
+ );
+ });
+ }
+
+ log(
+ '[%s][request_human_approve] All tool messages created, emitting human_approve_required event',
+ sessionLogId,
+ );
+
+ events.push({
+ pendingToolsCalling,
+ sessionId: newState.sessionId,
+ type: 'human_approve_required',
+ });
+
+ return { events, newState };
+ },
/**
* Finish executor
* Completes the runtime execution
diff --git a/src/store/chat/agents/createToolEngine.ts b/src/store/chat/agents/createToolEngine.ts
new file mode 100644
index 00000000000..adc068867e4
--- /dev/null
+++ b/src/store/chat/agents/createToolEngine.ts
@@ -0,0 +1,22 @@
+import { WorkingModel } from '@lobechat/types';
+
+import { getSearchConfig } from '@/helpers/getSearchConfig';
+import { createToolsEngine } from '@/helpers/toolEngineering';
+import { WebBrowsingManifest } from '@/tools/web-browsing';
+
+export const createAgentToolsEngine = (workingModel: WorkingModel) =>
+ createToolsEngine({
+ // Add WebBrowsingManifest as default tool
+ defaultToolIds: [WebBrowsingManifest.identifier],
+ // Create search-aware enableChecker for this request
+ enableChecker: ({ pluginId }) => {
+ // For WebBrowsingManifest, apply search logic
+ if (pluginId === WebBrowsingManifest.identifier) {
+ const searchConfig = getSearchConfig(workingModel.model, workingModel.provider);
+ return searchConfig.useApplicationBuiltinSearchTool;
+ }
+
+ // For all other plugins, enable by default
+ return true;
+ },
+ });
diff --git a/src/store/chat/slices/aiChat/actions/conversationControl.ts b/src/store/chat/slices/aiChat/actions/conversationControl.ts
index b1a7ecb491a..e8f57620410 100644
--- a/src/store/chat/slices/aiChat/actions/conversationControl.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationControl.ts
@@ -1,13 +1,19 @@
/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
// Disable the auto sort key eslint rule to make the code more logic and readable
+import { AgentRuntime, type AgentRuntimeContext } from '@lobechat/agent-runtime';
import { MESSAGE_CANCEL_FLAT } from '@lobechat/const';
import { produce } from 'immer';
import { StateCreator } from 'zustand/vanilla';
+import { getAgentStoreState } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/slices/chat';
+import { createAgentToolsEngine } from '@/store/chat/agents/createToolEngine';
import { ChatStore } from '@/store/chat/store';
import { setNamespace } from '@/utils/storeDebug';
+import { displayMessageSelectors } from '../../../selectors';
import { messageMapKey } from '../../../utils/messageMapKey';
+import { dbMessageSelectors } from '../../message/selectors';
import { MainSendMessageOperation } from '../initialState';
const n = setNamespace('ai');
@@ -32,6 +38,14 @@ export interface ConversationControlAction {
* Switches to a different branch of a message
*/
switchMessageBranch: (messageId: string, branchIndex: number) => Promise<void>;
+ /**
+ * Approve tool intervention
+ */
+ approveToolCalling: (toolMessageId: string, assistantGroupId: string) => Promise<void>;
+ /**
+ * Reject tool intervention
+ */
+ rejectToolCalling: (messageId: string, reason?: string) => Promise<void>;
/**
* Toggle sendMessage operation state
*/
@@ -131,6 +145,98 @@ export const conversationControl: StateCreator<
return undefined;
}
},
+ approveToolCalling: async (toolMessageId) => {
+ const { activeId, activeTopicId, activeThreadId, internal_execAgentRuntime } = get();
+
+ // 1. Get tool message and verify it exists
+ const toolMessage = dbMessageSelectors.getDbMessageById(toolMessageId)(get());
+ if (!toolMessage) return;
+
+ // 2. Update intervention status to approved
+ await get().optimisticUpdatePlugin(toolMessageId, { intervention: { status: 'approved' } });
+
+ // 3. Get current messages for state construction
+ const currentMessages = displayMessageSelectors.mainAIChats(get());
+
+ // 4. Get agent configuration and tools information
+ const agentStoreState = getAgentStoreState();
+ const agentConfigData = agentSelectors.currentAgentConfig(agentStoreState);
+
+ const toolsEngine = createAgentToolsEngine({
+ model: agentConfigData.model,
+ provider: agentConfigData.provider!,
+ });
+ const { enabledToolIds } = toolsEngine.generateToolsDetailed({
+ model: agentConfigData.model,
+ provider: agentConfigData.provider!,
+ toolIds: agentConfigData.plugins,
+ });
+ const toolManifestMap = Object.fromEntries(
+ toolsEngine.getEnabledPluginManifests(enabledToolIds).entries(),
+ );
+
+ // 5. Construct AgentState
+ const state = AgentRuntime.createInitialState({
+ sessionId: activeId,
+ messages: currentMessages,
+ maxSteps: 400,
+ metadata: {
+ sessionId: activeId,
+ topicId: activeTopicId,
+ threadId: activeThreadId,
+ },
+ toolManifestMap,
+ });
+
+ console.log('toolMessage:', toolMessage);
+ // 6. Construct AgentRuntimeContext with 'human_approved_tool' phase
+ const context: AgentRuntimeContext = {
+ phase: 'human_approved_tool',
+ payload: {
+ approvedToolCall: toolMessage.plugin,
+ parentMessageId: toolMessageId,
+ skipCreateToolMessage: true,
+ },
+ session: {
+ sessionId: activeId,
+ messageCount: currentMessages.length,
+ status: 'running',
+ stepCount: 0,
+ },
+ };
+
+ // 7. Execute agent runtime from tool message position
+ try {
+ await internal_execAgentRuntime({
+ messages: currentMessages,
+ parentMessageId: toolMessageId, // Start from tool message
+ parentMessageType: 'tool', // Type is 'tool'
+ threadId: activeThreadId,
+ initialState: state,
+ initialContext: context,
+ });
+ } catch (error) {
+ console.error('[approveToolCalling] Error executing agent runtime:', error);
+ }
+ },
+
+ rejectToolCalling: async (messageId, reason) => {
+ const toolMessage = dbMessageSelectors.getDbMessageById(messageId)(get());
+ if (!toolMessage) return;
+
+ // Optimistic update - update status to rejected and save reason
+ const intervention = {
+ rejectedReason: reason,
+ status: 'rejected',
+ } as const;
+ await get().optimisticUpdatePlugin(toolMessage.id, { intervention });
+
+ const toolContent = !!reason
+ ? `User reject this tool calling with reason: ${reason}`
+ : 'User reject this tool calling without reason';
+
+ await get().optimisticUpdateMessageContent(messageId, toolContent);
+ },
internal_updateSendMessageOperation: (key, value, actionName) => {
const operationKey = typeof key === 'string' ? key : messageMapKey(key.sessionId, key.topicId);
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index 6941ee0588b..d19eb35dd8a 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -1,6 +1,6 @@
/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
// Disable the auto sort key eslint rule to make the code more logic and readable
-import { AgentRuntime, type AgentRuntimeContext } from '@lobechat/agent-runtime';
+import { AgentRuntime, type AgentRuntimeContext, type AgentState } from '@lobechat/agent-runtime';
import { isDesktop } from '@lobechat/const';
import { knowledgeBaseQAPrompts } from '@lobechat/prompts';
import {
@@ -23,6 +23,7 @@ import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selector
import { getAgentStoreState } from '@/store/agent/store';
import { GeneralChatAgent } from '@/store/chat/agents/GeneralChatAgent';
import { createAgentExecutors } from '@/store/chat/agents/createAgentExecutors';
+import { createAgentToolsEngine } from '@/store/chat/agents/createToolEngine';
import { ChatStore } from '@/store/chat/store';
import { getFileStoreState } from '@/store/file/store';
import { setNamespace } from '@/utils/storeDebug';
@@ -88,6 +89,14 @@ export interface StreamingExecutorAction {
skipCreateFirstMessage?: boolean;
traceId?: string;
ragMetadata?: { ragQueryId: string; fileChunks: MessageSemanticSearchChunk[] };
+ /**
+ * Initial agent state (for resuming execution from a specific point)
+ */
+ initialState?: AgentState;
+ /**
+ * Initial agent runtime context (for resuming execution from a specific phase)
+ */
+ initialContext?: AgentRuntimeContext;
}) => Promise<void>;
}
@@ -397,6 +406,7 @@ export const streamingExecutor: StateCreator<
// ===========================================
// Step 1: RAG Preprocessing (if enabled)
// ===========================================
+ // Skip RAG preprocessing if initialState is provided (messages already preprocessed)
if (params.ragQuery && parentMessageType === 'user') {
const userMessageId = parentMessageId;
log('[internal_execAgentRuntime] RAG preprocessing start');
@@ -458,6 +468,17 @@ export const streamingExecutor: StateCreator<
provider: provider!,
},
});
+
+ const toolsEngine = createAgentToolsEngine({ model: model, provider: provider! });
+ const { enabledToolIds } = toolsEngine.generateToolsDetailed({
+ model: model,
+ provider: provider!,
+ toolIds: agentConfigData.plugins,
+ });
+ const toolManifestMap = Object.fromEntries(
+ toolsEngine.getEnabledPluginManifests(enabledToolIds).entries(),
+ );
+
const runtime = new AgentRuntime(agent, {
executors: createAgentExecutors({
get,
@@ -468,21 +489,24 @@ export const streamingExecutor: StateCreator<
}),
});
- // Create initial state
- let state = AgentRuntime.createInitialState({
- sessionId: activeId,
- messages,
- // Prevent infinite loops
- maxSteps: 400,
- metadata: {
+ // Create initial state or use provided state
+ let state =
+ params.initialState ||
+ AgentRuntime.createInitialState({
sessionId: activeId,
- topicId: activeTopicId,
- threadId: params.threadId,
- },
- });
+ messages,
+ // Prevent infinite loops
+ maxSteps: 400,
+ metadata: {
+ sessionId: activeId,
+ topicId: activeTopicId,
+ threadId: params.threadId,
+ },
+ toolManifestMap,
+ });
- // Initial context - use 'init' phase since state already contains messages
- let nextContext: AgentRuntimeContext = {
+ // Initial context - use provided context or create default 'init' phase
+ let nextContext: AgentRuntimeContext = params.initialContext || {
phase: 'init',
payload: { model, provider, parentMessageId: params.parentMessageId },
session: {
@@ -520,20 +544,24 @@ export const streamingExecutor: StateCreator<
// Handle completion and error events
for (const event of result.events) {
- if (event.type === 'done') {
- log('[internal_execAgentRuntime] Received done event');
- }
+ switch (event.type) {
+ case 'done': {
+ log('[internal_execAgentRuntime] Received done event');
+ break;
+ }
- if (event.type === 'error') {
- log('[internal_execAgentRuntime] Received error event: %o', event.error);
- // Find the assistant message to update error
- const currentMessages = get().messagesMap[messageKey] || [];
- const assistantMessage = currentMessages.findLast((m) => m.role === 'assistant');
- if (assistantMessage) {
- await messageService.updateMessageError(assistantMessage.id, event.error);
+ case 'error': {
+ log('[internal_execAgentRuntime] Received error event: %o', event.error);
+ // Find the assistant message to update error
+ const currentMessages = get().messagesMap[messageKey] || [];
+ const assistantMessage = currentMessages.findLast((m) => m.role === 'assistant');
+ if (assistantMessage) {
+ await messageService.updateMessageError(assistantMessage.id, event.error);
+ }
+ const finalMessages = get().messagesMap[messageKey] || [];
+ get().replaceMessages(finalMessages);
+ break;
}
- const finalMessages = get().messagesMap[messageKey] || [];
- get().replaceMessages(finalMessages);
}
}
diff --git a/src/store/chat/slices/message/reducer.ts b/src/store/chat/slices/message/reducer.ts
index a9ed7b243e4..bdbfdc8ff6b 100644
--- a/src/store/chat/slices/message/reducer.ts
+++ b/src/store/chat/slices/message/reducer.ts
@@ -3,6 +3,7 @@ import {
ChatPluginPayload,
ChatToolPayload,
CreateMessageParams,
+ MessagePluginItem,
UIChatMessage,
} from '@lobechat/types';
import isEqual from 'fast-deep-equal';
@@ -47,7 +48,7 @@ interface UpdatePluginState {
interface UpdateMessagePlugin {
id: string;
type: 'updateMessagePlugin';
- value: Partial<ChatPluginPayload>;
+ value: Partial<MessagePluginItem>;
}
interface UpdateMessageTools {
diff --git a/src/store/chat/slices/plugin/actions/optimisticUpdate.ts b/src/store/chat/slices/plugin/actions/optimisticUpdate.ts
index 9dc7aa20c20..6a7f71f61a4 100644
--- a/src/store/chat/slices/plugin/actions/optimisticUpdate.ts
+++ b/src/store/chat/slices/plugin/actions/optimisticUpdate.ts
@@ -1,5 +1,5 @@
/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */
-import { ChatMessageError, ChatToolPayload } from '@lobechat/types';
+import { ChatMessageError, ChatToolPayload, MessagePluginItem } from '@lobechat/types';
import isEqual from 'fast-deep-equal';
import { StateCreator } from 'zustand/vanilla';
@@ -29,6 +29,11 @@ export interface PluginOptimisticUpdateAction {
replace?: boolean,
) => Promise<void>;
+ /**
+ * Update plugin with optimistic update (generic method for any plugin field)
+ */
+ optimisticUpdatePlugin: (id: string, value: Partial<MessagePluginItem>) => Promise<void>;
+
/**
* Add tool to assistant message with optimistic update
*/
@@ -119,6 +124,26 @@ export const pluginOptimisticUpdate: StateCreator<
await refreshMessages();
},
+ optimisticUpdatePlugin: async (id, value) => {
+ const { replaceMessages } = get();
+
+ // optimistic update
+ get().internal_dispatchMessage({
+ id,
+ type: 'updateMessagePlugin',
+ value,
+ });
+
+ const result = await messageService.updateMessagePlugin(id, value, {
+ sessionId: get().activeId,
+ topicId: get().activeTopicId,
+ });
+
+ if (result?.success && result.messages) {
+ replaceMessages(result.messages);
+ }
+ },
+
optimisticAddToolToAssistantMessage: async (id, tool) => {
const assistantMessage = displayMessageSelectors.getDisplayMessageById(id)(get());
if (!assistantMessage) return;
diff --git a/src/store/user/slices/settings/action.ts b/src/store/user/slices/settings/action.ts
index 9d536000960..836fc2febb5 100644
--- a/src/store/user/slices/settings/action.ts
+++ b/src/store/user/slices/settings/action.ts
@@ -18,6 +18,7 @@ import { difference } from '@/utils/difference';
import { merge } from '@/utils/merge';
export interface UserSettingsAction {
+ addToolToAllowList: (toolKey: string) => Promise<void>;
importAppSettings: (settings: UserSettings) => Promise<void>;
importUrlShareSettings: (settingsParams: string | null) => Promise<void>;
internal_createSignal: () => AbortController;
@@ -39,6 +40,20 @@ export const createSettingsSlice: StateCreator<
[],
UserSettingsAction
> = (set, get) => ({
+ addToolToAllowList: async (toolKey) => {
+ const currentAllowList = get().settings.tool?.humanIntervention?.allowList || [];
+
+ if (currentAllowList.includes(toolKey)) return;
+
+ await get().setSettings({
+ tool: {
+ humanIntervention: {
+ allowList: [...currentAllowList, toolKey],
+ },
+ },
+ });
+ },
+
importAppSettings: async (importAppSettings) => {
const { setSettings } = get();