package com.easyagents.agent.runtime.agentscope;

import com.easyagents.agent.runtime.*;
import com.easyagents.agent.runtime.event.*;
import com.easyagents.agent.runtime.event.interceptor.AutoContextInterceptor;
import com.easyagents.agent.runtime.event.interceptor.ToolHitlInterceptor;
import com.easyagents.agent.runtime.event.observer.AgentRuntimeErrorObserver;
import com.easyagents.agent.runtime.event.observer.ReasoningLifecycleObserver;
import com.easyagents.agent.runtime.event.observer.SkillExecutionObserver;
import com.easyagents.agent.runtime.event.observer.ToolExecutionObserver;
import com.easyagents.agent.runtime.hitl.AgentResumeToken;
import com.easyagents.agent.runtime.knowledge.AgentKnowledgeDocument;
import com.easyagents.agent.runtime.knowledge.AgentKnowledgeRetrievalResult;
import com.easyagents.agent.runtime.knowledge.AgentKnowledgeSpec;
import com.easyagents.agent.runtime.memory.AgentMemoryCompressionParameter;
import com.easyagents.agent.runtime.memory.AgentMemoryPolicy;
import com.easyagents.agent.runtime.memory.AgentMemorySnapshot;
import com.easyagents.agent.runtime.message.AgentMessage;
import com.easyagents.agent.runtime.message.AgentMessageRole;
import com.easyagents.agent.runtime.message.AgentMediaBlock;
import com.easyagents.agent.runtime.model.AgentModelSpec;
import com.easyagents.agent.runtime.persistence.session.memory.InMemoryAgentSessionStore;
import com.easyagents.agent.runtime.skill.AgentSkillBoxSpec;
import com.easyagents.agent.runtime.skill.AgentSkillRuntimeContext;
import com.easyagents.agent.runtime.skill.AgentSkillSpec;
import com.easyagents.agent.runtime.tool.AgentToolResult;
import com.easyagents.agent.runtime.tool.AgentToolSpec;
import com.easyagents.agent.runtime.tool.operate.AgentOperateToolAdapter;
import com.easyagents.agent.runtime.tool.operate.AgentOperateToolSpec;
import com.easyagents.agent.runtime.tool.operate.AgentOperateToolType;
import io.agentscope.core.ReActAgent;
import io.agentscope.core.hook.*;
import io.agentscope.core.memory.autocontext.AutoContextHook;
import io.agentscope.core.memory.autocontext.AutoContextMemory;
import io.agentscope.core.message.*;
import io.agentscope.core.model.ChatResponse;
import io.agentscope.core.model.GenerateOptions;
import io.agentscope.core.model.Model;
import io.agentscope.core.model.ToolSchema;
import io.agentscope.core.skill.SkillBox;
import io.agentscope.core.tool.AgentTool;
import io.agentscope.core.tool.Toolkit;
import io.agentscope.core.tool.mcp.McpClientWrapper;
import io.modelcontextprotocol.spec.McpSchema;
import org.junit.Assert;
import org.junit.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;

import java.lang.reflect.Field;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BooleanSupplier;

/**
 * 测试有状态 AgentScope 运行时。
 */
public class AgentScopeStatefulRuntimeTest {

    @Test(expected = AgentRuntimeException.class)
    public void shouldRejectStreamBeforeInit() {
        AgentScopeReActRuntime runtime = fakeRuntime();

        runtime.stream(AgentMessage.text(AgentMessageRole.USER, "hello"));
    }

    @Test(expected = AgentRuntimeException.class)
    public void shouldRejectEmptyStreamMessage() {
        AgentScopeReActRuntime runtime = fakeRuntime();
        AgentMessage message = new AgentMessage();
        runtime.init(initRequest());

        runtime.stream(message);
    }

    @Test(expected = AgentRuntimeException.class)
    public void shouldRejectImageWhenModelCapabilityIsDisabled() {
        AgentScopeReActRuntime runtime = fakeRuntime();
        AgentInitRequest request = initRequest();
        runtime.init(request);
        AgentMessage message = new AgentMessage();
        message.setRole(AgentMessageRole.USER);
        AgentMediaBlock image = new AgentMediaBlock("image");
        image.setReference("draft:upload-1");
        message.setContentBlocks(List.of(image));

        runtime.stream(message);
    }

    @Test(expected = AgentRuntimeException.class)
    public void shouldRejectDuplicateInit() {
        AgentScopeReActRuntime runtime = fakeRuntime();
        AgentInitRequest request = initRequest();

        runtime.init(request);
        runtime.init(request);
    }

    @Test(expected = AgentRuntimeException.class)
    public void shouldRequireSessionStore() {
        AgentInitRequest request = initRequest();
        request.setSessionStore(null);

        fakeRuntime().init(request);
    }

    @Test
    public void shouldRegisterUnifiedRuntimeHookForStatefulAutoContextRuntime() {
        AgentInitRequest request = initRequest();
        request.getAgentDefinition().setMemoryPolicy(AgentMemoryPolicy.autoContext());
        AgentScopeReActRuntime runtime = fakeRuntime();

        runtime.init(request);

        Assert.assertTrue(runtime.getAgent().getHooks().stream().anyMatch(this::isRuntimeHook));
        Assert.assertFalse(runtime.getAgent().getHooks().stream().anyMatch(AutoContextHook.class::isInstance));
    }

    @Test
    public void shouldKeepSystemPromptUnchangedWithoutAsyncTool() {
        AgentScopeReActRuntime runtime = fakeRuntime();

        runtime.init(initRequest());

        Assert.assertEquals("system", runtime.getAgent().getSysPrompt());
    }

    @Test
    public void shouldAppendAsyncToolProtocolPromptWhenAsyncToolsExist() {
        AgentInitRequest request = initRequest();
        AgentToolSpec submit = new AgentToolSpec();
        submit.setName("demo_submit");
        submit.setDescription("submit demo");
        submit.getMetadata().put("asyncTool", true);
        submit.getMetadata().put("asyncToolPhase", "submit");
        request.getAgentDefinition().setToolSpecs(List.of(submit));
        request.setToolInvokers(Map.of("demo_submit", (arguments, context) -> AgentToolResult.success("submitted")));
        AgentScopeReActRuntime runtime = fakeRuntime();

        runtime.init(request);

        Assert.assertTrue(runtime.getAgent().getSysPrompt().startsWith("system"));
        Assert.assertTrue(runtime.getAgent().getSysPrompt().contains("Async tool protocol:"));
        Assert.assertTrue(runtime.getAgent().getSysPrompt().contains("These are internal execution phases."));
        Assert.assertTrue(runtime.getAgent().getSysPrompt().contains("call its submit sub-tool first with the user-provided arguments by default"));
        Assert.assertTrue(runtime.getAgent().getSysPrompt().contains("immediately call observe"));
    }

    @Test
    public void shouldEmitSideEventWithRuntimeIdentityFromBridge() throws Exception {
        AgentRuntimeExecutionContext context = new AgentRuntimeExecutionContext();
        AgentDefinition definition = new AgentDefinition();
        definition.setAgentId("agent-bridge");
        context.setAgentDefinition(definition);
        context.setRequestId("request-bridge");
        context.setTraceId("trace-bridge");
        context.setSessionId("session-bridge");
        context.setMetadata(Map.of("tenantId", "tenant-1"));
        Sinks.Many<AgentRuntimeEvent> sink = Sinks.many().replay().all();
        AgentRuntimeEventBridge bridge = AgentRuntimeEventBridge.fixed(context, sink);

        bridge.emit(AgentRuntimeEvent.of(AgentRuntimeEventType.KNOWLEDGE_RETRIEVAL));
        AgentRuntimeEvent event = sink.asFlux().take(1).collectList().toFuture().get(3, TimeUnit.SECONDS).get(0);

        Assert.assertEquals("trace-bridge", event.getTraceId());
        Assert.assertEquals("session-bridge", event.getSessionId());
        Assert.assertEquals("agent-bridge", event.getAgentId());
        Assert.assertEquals("request-bridge", event.getMetadata().get("requestId"));
        Assert.assertEquals("tenant-1", event.getMetadata().get("tenantId"));
    }

    @Test
    public void shouldKeepAutoContextInterceptorInsideUnifiedRuntimeHook() throws Exception {
        AgentInitRequest request = initRequest();
        request.getAgentDefinition().setMemoryPolicy(AgentMemoryPolicy.autoContext());
        AgentScopeReActRuntime runtime = fakeRuntime();

        runtime.init(request);
        AgentScopeRuntimeHook runtimeHook = runtime.getAgent().getHooks().stream()
                .filter(AgentScopeRuntimeHook.class::isInstance)
                .map(AgentScopeRuntimeHook.class::cast)
                .findFirst()
                .orElseThrow();
        Field managerField = AgentScopeRuntimeHook.class.getDeclaredField("observationManager");
        managerField.setAccessible(true);
        AgentRuntimeObservationManager manager = (AgentRuntimeObservationManager) managerField.get(runtimeHook);
        Field interceptorsField = AgentRuntimeObservationManager.class.getDeclaredField("interceptors");
        interceptorsField.setAccessible(true);
        @SuppressWarnings("unchecked")
        List<AgentRuntimeInterceptor> interceptors = (List<AgentRuntimeInterceptor>) interceptorsField.get(manager);

        Assert.assertTrue(interceptors.stream().anyMatch(AutoContextInterceptor.class::isInstance));
    }

    @Test
    public void shouldKeepToolHitlInterceptorInsideUnifiedRuntimeHook() throws Exception {
        AgentInitRequest request = initRequest();
        AgentToolSpec toolSpec = new AgentToolSpec();
        toolSpec.setName("search");
        toolSpec.setDescription("search");
        toolSpec.setApprovalRequired(true);
        request.getAgentDefinition().setToolSpecs(List.of(toolSpec));
        request.setToolInvokers(Map.of("search", (arguments, context) -> AgentToolResult.success("tool result")));
        AgentScopeReActRuntime runtime = runtimeWithModel(List.of(ChatResponse.builder()
                .id("tool-call-message")
                .content(List.of(ToolUseBlock.builder()
                        .id("call-search")
                        .name("search")
                        .input(Map.of("q", "easyflow"))
                        .build()))
                .finishReason("tool_calls")
                .build()));

        runtime.init(request);
        AgentScopeRuntimeHook runtimeHook = runtime.getAgent().getHooks().stream()
                .filter(AgentScopeRuntimeHook.class::isInstance)
                .map(AgentScopeRuntimeHook.class::cast)
                .findFirst()
                .orElseThrow();
        Field managerField = AgentScopeRuntimeHook.class.getDeclaredField("observationManager");
        managerField.setAccessible(true);
        AgentRuntimeObservationManager manager = (AgentRuntimeObservationManager) managerField.get(runtimeHook);
        Field interceptorsField = AgentRuntimeObservationManager.class.getDeclaredField("interceptors");
        interceptorsField.setAccessible(true);
        @SuppressWarnings("unchecked")
        List<AgentRuntimeInterceptor> interceptors = (List<AgentRuntimeInterceptor>) interceptorsField.get(manager);

        Assert.assertTrue(interceptors.stream().anyMatch(ToolHitlInterceptor.class::isInstance));
    }

    @Test
    public void shouldRegisterOperateToolsIntoToolkit() {
        AgentInitRequest request = initRequest();
        request.getAgentDefinition().setOperateToolSpecs(List.of(
                operateToolSpec(AgentOperateToolType.READ_FILE),
                operateToolSpec(AgentOperateToolType.WRITE_FILE),
                operateToolSpec(AgentOperateToolType.SHELL)));
        AgentScopeReActRuntime runtime = fakeRuntime();

        runtime.init(request);

        Toolkit toolkit = runtime.getAgent().getToolkit();
        Assert.assertNotNull(toolkit.getTool(AgentOperateToolAdapter.VIEW_TEXT_FILE_TOOL));
        Assert.assertNotNull(toolkit.getTool(AgentOperateToolAdapter.LIST_DIRECTORY_TOOL));
        Assert.assertNotNull(toolkit.getTool(AgentOperateToolAdapter.WRITE_TEXT_FILE_TOOL));
        Assert.assertNotNull(toolkit.getTool(AgentOperateToolAdapter.INSERT_TEXT_FILE_TOOL));
        Assert.assertNotNull(toolkit.getTool(AgentOperateToolAdapter.EXECUTE_SHELL_COMMAND_TOOL));
    }

    @Test
    public void shouldSuspendShellOperateToolWithToolHitlInterceptor() {
        AgentInitRequest request = initRequest();
        AgentOperateToolSpec shell = operateToolSpec(AgentOperateToolType.SHELL);
        shell.setShellAllowedCommands(Set.of());
        request.getAgentDefinition().setOperateToolSpecs(List.of(shell));
        AgentScopeReActRuntime runtime = runtimeWithModel(List.of(ChatResponse.builder()
                .id("shell-call-message")
                .content(List.of(ToolUseBlock.builder()
                        .id("call-shell")
                        .name(AgentOperateToolAdapter.EXECUTE_SHELL_COMMAND_TOOL)
                        .input(Map.of("command", "echo hello"))
                        .build()))
                .finishReason("tool_calls")
                .build()));

        runtime.init(request);
        List<AgentRuntimeEvent> events = runtime.stream(AgentMessage.text(AgentMessageRole.USER, "run shell"))
                .collectList()
                .block(Duration.ofSeconds(5));

        Assert.assertNotNull(events);
        Assert.assertTrue(events.stream().anyMatch(event -> event.getEventType() == AgentRuntimeEventType.TOOL_APPROVAL_REQUIRED));
        Assert.assertTrue(events.stream().anyMatch(event -> event.getEventType() == AgentRuntimeEventType.SUSPENDED));
    }

    @Test(expected = AgentRuntimeException.class)
    public void shouldRejectOperateToolNameConflictWithBusinessTool() {
        AgentInitRequest request = initRequest();
        AgentToolSpec toolSpec = new AgentToolSpec();
        toolSpec.setName(AgentOperateToolAdapter.EXECUTE_SHELL_COMMAND_TOOL);
        toolSpec.setDescription("conflict");
        request.getAgentDefinition().setToolSpecs(List.of(toolSpec));
        request.setToolInvokers(Map.of(AgentOperateToolAdapter.EXECUTE_SHELL_COMMAND_TOOL,
                (arguments, context) -> AgentToolResult.success("ok")));
        request.getAgentDefinition().setOperateToolSpecs(List.of(operateToolSpec(AgentOperateToolType.SHELL)));

        fakeRuntime().init(request);
    }

    @Test
    public void shouldEnablePendingToolRecoveryForRejectedHitlContinuation() {
        AgentScopeReActRuntime runtime = fakeRuntime();

        runtime.init(initRequest());

        Assert.assertTrue(runtime.getAgent().getHooks().stream()
                .anyMatch(PendingToolRecoveryHook.class::isInstance));
    }

    @Test
    public void shouldCloseMcpClientsWhenRuntimeCloses() throws Exception {
        AgentScopeReActRuntime runtime = fakeRuntime();
        FakeMcpClientWrapper client = new FakeMcpClientWrapper("mcp-close");
        Field mcpClientsField = AgentScopeReActRuntime.class.getDeclaredField("mcpClients");
        mcpClientsField.setAccessible(true);
        @SuppressWarnings("unchecked")
        List<McpClientWrapper> clients = (List<McpClientWrapper>) mcpClientsField.get(runtime);
        clients.add(client);

        runtime.close();

        Assert.assertTrue(client.closed.get());
        Assert.assertTrue(clients.isEmpty());
    }

    @Test
    public void shouldCloseMcpClientsEvenWhenRuntimeIsStreaming() throws Exception {
        AgentScopeReActRuntime runtime = fakeRuntime();
        FakeMcpClientWrapper client = new FakeMcpClientWrapper("mcp-close-streaming");
        Field mcpClientsField = AgentScopeReActRuntime.class.getDeclaredField("mcpClients");
        mcpClientsField.setAccessible(true);
        @SuppressWarnings("unchecked")
        List<McpClientWrapper> clients = (List<McpClientWrapper>) mcpClientsField.get(runtime);
        clients.add(client);
        Field runningField = AgentScopeReActRuntime.class.getDeclaredField("running");
        runningField.setAccessible(true);
        AtomicBoolean running = (AtomicBoolean) runningField.get(runtime);
        running.set(true);

        runtime.close();

        Assert.assertTrue(client.closed.get());
        Assert.assertTrue(clients.isEmpty());
    }

    @Test
    public void shouldEmitAutoContextCompressionEventsFromInterceptor() throws Exception {
        AgentInitRequest request = initRequest();
        AgentMemoryCompressionParameter parameter = new AgentMemoryCompressionParameter();
        parameter.setMsgThreshold(3);
        parameter.setLastKeep(1);
        parameter.setLargePayloadThreshold(20);
        AgentMemoryPolicy policy = AgentMemoryPolicy.autoContext();
        policy.setCompressionParameter(parameter);
        policy.setMaxAttachedMessageCount(10);
        request.getAgentDefinition().setMemoryPolicy(policy);
        AgentScopeMemoryBuildResult memoryResult = new AgentScopeMemoryAdapter()
                .createMemoryResult(compressionSnapshot(), policy, new FakeAgentScopeModelFactory()
                        .create(request.getAgentDefinition().getModelSpec(), request.getAgentDefinition().getGenerationOptions()));
        ReActAgent agent = ReActAgent.builder()
                .name("agent-name")
                .sysPrompt("system")
                .model(new FakeAgentScopeModelFactory()
                        .create(request.getAgentDefinition().getModelSpec(), request.getAgentDefinition().getGenerationOptions()))
                .memory(memoryResult.getMemory())
                .toolkit(new Toolkit())
                .build();
        Sinks.Many<AgentRuntimeEvent> sink = Sinks.many().replay().all();
        AutoContextInterceptor interceptor = new AutoContextInterceptor(
                AgentRuntimeEventBridge.fixed(executionContext(), sink), memoryResult.getAutoContextConfig());
        CompletableFuture<List<AgentRuntimeEvent>> eventsFuture = sink.asFlux().take(2).collectList().toFuture();
        PreReasoningEvent event = new PreReasoningEvent(agent, "fake-model", null,
                List.of(Msg.builder()
                        .role(MsgRole.SYSTEM)
                        .name("system")
                        .content(TextBlock.builder().text("system").build())
                        .build()));

        interceptor.intercept(event).block();
        List<AgentRuntimeEvent> events = eventsFuture.get(3, TimeUnit.SECONDS);

        Assert.assertEquals(AgentRuntimeEventType.MEMORY_COMPRESSION_STARTED, events.get(0).getEventType());
        Assert.assertEquals(AgentRuntimeEventType.MEMORY_COMPRESSION_COMPLETED, events.get(1).getEventType());
        Assert.assertEquals("memory-compression", events.get(0).getPayload().get("statusKey"));
        Assert.assertEquals(Boolean.TRUE, events.get(1).getPayload().get("compressed"));
        Assert.assertTrue(((Number) events.get(1).getPayload().get("eventCount")).intValue() > 0);
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> compressionEvents = (List<Map<String, Object>>) events.get(1).getPayload().get("events");
        Assert.assertFalse(compressionEvents.isEmpty());
        Assert.assertTrue(event.getInputMessages().get(0).getTextContent().contains("CONTEXT_OFFLOAD"));
        Assert.assertTrue(((AutoContextMemory) agent.getMemory()).getMessages().stream()
                .anyMatch(message -> message.getTextContent() != null
                        && message.getTextContent().contains("CONTEXT_OFFLOAD")));
    }

    @Test
    public void shouldNotEmitAutoContextCompressionEventsWhenThresholdIsNotReached() {
        AgentInitRequest request = initRequest();
        AgentMemoryCompressionParameter parameter = new AgentMemoryCompressionParameter();
        parameter.setMsgThreshold(10);
        AgentMemoryPolicy policy = AgentMemoryPolicy.autoContext();
        policy.setCompressionParameter(parameter);
        request.getAgentDefinition().setMemoryPolicy(policy);
        AgentScopeMemoryBuildResult memoryResult = new AgentScopeMemoryAdapter()
                .createMemoryResult(null, policy, new FakeAgentScopeModelFactory()
                        .create(request.getAgentDefinition().getModelSpec(), request.getAgentDefinition().getGenerationOptions()));
        memoryResult.getMemory().addMessage(Msg.builder().role(MsgRole.USER).textContent("hello").build());
        ReActAgent agent = ReActAgent.builder()
                .name("agent-name")
                .sysPrompt("system")
                .model(new FakeAgentScopeModelFactory()
                        .create(request.getAgentDefinition().getModelSpec(), request.getAgentDefinition().getGenerationOptions()))
                .memory(memoryResult.getMemory())
                .toolkit(new Toolkit())
                .build();
        Sinks.Many<AgentRuntimeEvent> sink = Sinks.many().replay().all();
        AutoContextInterceptor interceptor = new AutoContextInterceptor(
                AgentRuntimeEventBridge.fixed(executionContext(), sink), memoryResult.getAutoContextConfig());
        PreReasoningEvent event = new PreReasoningEvent(agent, "fake-model", null,
                List.of(Msg.builder().role(MsgRole.SYSTEM).textContent("system").build()));

        interceptor.intercept(event).block();

        Assert.assertTrue(sink.asFlux().take(Duration.ofMillis(100)).collectList().block().isEmpty());
        Assert.assertTrue(event.getInputMessages().get(0).getTextContent().contains("CONTEXT_OFFLOAD"));
    }

    @Test
    public void shouldEmitNoCompressionCompletedEventWhenCompressionIsSkipped() throws Exception {
        AgentInitRequest request = initRequest();
        AgentMemoryCompressionParameter parameter = new AgentMemoryCompressionParameter();
        parameter.setMsgThreshold(1);
        parameter.setLastKeep(1);
        parameter.setMinCompressionTokenThreshold(300);
        AgentMemoryPolicy policy = AgentMemoryPolicy.autoContext();
        policy.setCompressionParameter(parameter);
        request.getAgentDefinition().setMemoryPolicy(policy);
        AgentScopeMemoryBuildResult memoryResult = new AgentScopeMemoryAdapter()
                .createMemoryResult(null, policy, new FakeAgentScopeModelFactory()
                        .create(request.getAgentDefinition().getModelSpec(), request.getAgentDefinition().getGenerationOptions()));
        memoryResult.getMemory().addMessage(Msg.builder().role(MsgRole.USER).textContent("hi").build());
        ReActAgent agent = ReActAgent.builder()
                .name("agent-name")
                .sysPrompt("system")
                .model(new FakeAgentScopeModelFactory()
                        .create(request.getAgentDefinition().getModelSpec(), request.getAgentDefinition().getGenerationOptions()))
                .memory(memoryResult.getMemory())
                .toolkit(new Toolkit())
                .build();
        Sinks.Many<AgentRuntimeEvent> sink = Sinks.many().replay().all();
        AutoContextInterceptor interceptor = new AutoContextInterceptor(
                AgentRuntimeEventBridge.fixed(executionContext(), sink), memoryResult.getAutoContextConfig());
        CompletableFuture<List<AgentRuntimeEvent>> eventsFuture = sink.asFlux().take(2).collectList().toFuture();
        PreReasoningEvent event = new PreReasoningEvent(agent, "fake-model", null,
                List.of(Msg.builder().role(MsgRole.SYSTEM).textContent("system").build()));

        interceptor.intercept(event).block();
        List<AgentRuntimeEvent> events = eventsFuture.get(3, TimeUnit.SECONDS);

        Assert.assertEquals(AgentRuntimeEventType.MEMORY_COMPRESSION_STARTED, events.get(0).getEventType());
        Assert.assertEquals(AgentRuntimeEventType.MEMORY_COMPRESSION_COMPLETED, events.get(1).getEventType());
        Assert.assertEquals(Boolean.FALSE, events.get(1).getPayload().get("compressed"));
        Assert.assertEquals("无需压缩上下文", events.get(1).getPayload().get("label"));
        Assert.assertEquals(0, ((Number) events.get(1).getPayload().get("eventCount")).intValue());
        Assert.assertTrue(event.getInputMessages().get(0).getTextContent().contains("CONTEXT_OFFLOAD"));
    }

    @Test
    public void shouldRegisterContextReloadToolFromAutoContextInterceptor() {
        AgentMemoryPolicy policy = AgentMemoryPolicy.autoContext();
        AgentScopeMemoryBuildResult memoryResult = new AgentScopeMemoryAdapter()
                .createMemoryResult(null, policy, new FakeAgentScopeModelFactory().create(new AgentModelSpec(), null));
        ReActAgent agent = ReActAgent.builder()
                .name("agent-name")
                .model(new FakeAgentScopeModelFactory().create(new AgentModelSpec(), null))
                .memory(memoryResult.getMemory())
                .toolkit(new Toolkit())
                .build();
        Sinks.Many<AgentRuntimeEvent> sink = Sinks.many().replay().all();
        AutoContextInterceptor interceptor = new AutoContextInterceptor(
                AgentRuntimeEventBridge.fixed(executionContext(), sink), memoryResult.getAutoContextConfig());

        interceptor.intercept(new PreCallEvent(agent, List.of())).block();

        Assert.assertTrue(interceptor.isRegistered());
        Assert.assertNotNull(agent.getToolkit().getTool("context_reload"));
    }

    @Test
    public void shouldEmitToolCallAndResultFromToolExecutionObserver() throws Exception {
        AgentRuntimeExecutionContext context = executionContext();
        Sinks.Many<AgentRuntimeEvent> sink = Sinks.many().replay().all();
        AgentRuntimeEventBridge bridge = AgentRuntimeEventBridge.fixed(context, sink);
        AgentToolSpec toolSpec = new AgentToolSpec();
        toolSpec.setName("search");
        toolSpec.getMetadata().put("toolDisplayName", "Search Tool");
        toolSpec.getMetadata().put("rawMcpToolName", "search");
        ToolExecutionObserver observer = new ToolExecutionObserver(bridge, null, List.of(toolSpec));
        ReActAgent agent = initializedAgent();
        Toolkit toolkit = agent.getToolkit();
        ToolUseBlock toolUse = ToolUseBlock.builder()
                .id("call-1")
                .name("search")
                .input(Map.of("q", "easyflow"))
                .build();
        ToolResultBlock toolResult = ToolResultBlock.of("call-1", "search",
                TextBlock.builder().text("done").build(), Map.of("success", true));

        observer.observe(new PreActingEvent(agent, toolkit, toolUse)).block();
        observer.observe(new PostActingEvent(agent, toolkit, toolUse, toolResult)).block();
        List<AgentRuntimeEvent> events = sink.asFlux().take(2).collectList().toFuture().get(3, TimeUnit.SECONDS);

        Assert.assertEquals(AgentRuntimeEventType.TOOL_CALL, events.get(0).getEventType());
        Assert.assertEquals("RUNNING", events.get(0).getPayload().get("status"));
        Assert.assertEquals("PRE_ACTING", events.get(0).getPayload().get("phase"));
        Assert.assertEquals("Search Tool", events.get(0).getPayload().get("toolDisplayName"));
        Assert.assertEquals("search", events.get(0).getPayload().get("rawMcpToolName"));
        Assert.assertEquals(AgentRuntimeEventType.TOOL_RESULT, events.get(1).getEventType());
        Assert.assertEquals("SUCCESS", events.get(1).getPayload().get("status"));
        Assert.assertEquals("POST_ACTING", events.get(1).getPayload().get("phase"));
        Assert.assertEquals("Search Tool", events.get(1).getPayload().get("toolDisplayName"));
    }

    @Test
    public void shouldEmitSkillLifecycleEventsFromSkillExecutionObserver() throws Exception {
        AgentRuntimeExecutionContext context = executionContext();
        Sinks.Many<AgentRuntimeEvent> sink = Sinks.many().replay().all();
        AgentRuntimeEventBridge bridge = AgentRuntimeEventBridge.fixed(context, sink);
        AgentSkillRuntimeContext skillContext = AgentSkillRuntimeContext.from(skillBoxSpec());
        Toolkit toolkit = new Toolkit();
        SkillBox skillBox = skillBox(toolkit);
        SkillExecutionObserver observer = new SkillExecutionObserver(bridge, skillContext, skillBox);
        ReActAgent agent = initializedAgent();
        toolkit.updateToolGroups(List.of("skill-1_skill_tools"), true);
        ToolUseBlock loadSkill = ToolUseBlock.builder()
                .id("skill-call-1")
                .name(AgentSkillRuntimeContext.LOAD_SKILL_TOOL_NAME)
                .input(Map.of("skillId", "skill-1", "path", "SKILL.md"))
                .build();
        ToolResultBlock loadResult = ToolResultBlock.of("skill-call-1",
                AgentSkillRuntimeContext.LOAD_SKILL_TOOL_NAME,
                TextBlock.builder().text("Successfully loaded skill: skill-1").build(), Map.of("success", true));
        ToolUseBlock skillToolUse = ToolUseBlock.builder()
                .id("skill-step-1")
                .name("search")
                .input(Map.of("q", "easyflow"))
                .build();
        ToolResultBlock skillToolResult = ToolResultBlock.of("skill-step-1", "search",
                TextBlock.builder().text("done").build(), Map.of("success", true));

        observer.observe(new PreActingEvent(agent, toolkit, loadSkill)).block();
        observer.observe(new PostActingEvent(agent, toolkit, loadSkill, loadResult)).block();
        observer.observe(new PreActingEvent(agent, toolkit, skillToolUse)).block();
        observer.observe(new PostActingEvent(agent, toolkit, skillToolUse, skillToolResult)).block();
        List<AgentRuntimeEvent> events = sink.asFlux().take(4).collectList().toFuture().get(3, TimeUnit.SECONDS);

        Assert.assertEquals(AgentRuntimeEventType.SKILL_CALL, events.get(0).getEventType());
        Assert.assertEquals(AgentRuntimeEventType.SKILL_RESULT, events.get(1).getEventType());
        Assert.assertTrue(skillContext.isSkillActive("skill-1"));
        Assert.assertEquals(AgentRuntimeEventType.SKILL_STEP, events.get(2).getEventType());
        Assert.assertEquals("TOOL_CALL", events.get(2).getPayload().get("stepType"));
        Assert.assertEquals(AgentRuntimeEventType.SKILL_STEP, events.get(3).getEventType());
        Assert.assertEquals("TOOL_RESULT", events.get(3).getPayload().get("stepType"));
        Assert.assertEquals("skill-1", events.get(3).getPayload().get("skillId"));
    }

    @Test
    public void shouldUseAgentScopeSkillStateWhenSkillLoadReturnsErrorText() throws Exception {
        AgentRuntimeExecutionContext context = executionContext();
        Sinks.Many<AgentRuntimeEvent> sink = Sinks.many().replay().all();
        AgentRuntimeEventBridge bridge = AgentRuntimeEventBridge.fixed(context, sink);
        AgentSkillRuntimeContext skillContext = AgentSkillRuntimeContext.from(skillBoxSpec());
        Toolkit toolkit = new Toolkit();
        SkillBox skillBox = skillBox(toolkit);
        SkillExecutionObserver observer = new SkillExecutionObserver(bridge, skillContext, skillBox);
        ReActAgent agent = initializedAgent();
        ToolUseBlock loadSkill = ToolUseBlock.builder()
                .id("skill-call-error")
                .name(AgentSkillRuntimeContext.LOAD_SKILL_TOOL_NAME)
                .input(Map.of("skillId", "skill-1", "path", "missing.md"))
                .build();

        skillBox.getSkill("skill-1").getResource("missing.md");
        toolkit.updateToolGroups(List.of("skill-1_skill_tools"), true);
        ToolResultBlock loadResult = ToolResultBlock.of("skill-call-error",
                AgentSkillRuntimeContext.LOAD_SKILL_TOOL_NAME,
                TextBlock.builder().text("Error: Resource not found").build(), Map.of("success", true));
        observer.observe(new PreActingEvent(agent, toolkit, loadSkill)).block();
        observer.observe(new PostActingEvent(agent, toolkit, loadSkill, loadResult)).block();
        List<AgentRuntimeEvent> events = sink.asFlux().take(2).collectList().toFuture().get(3, TimeUnit.SECONDS);

        Assert.assertEquals(AgentRuntimeEventType.SKILL_RESULT, events.get(1).getEventType());
        Assert.assertEquals(Boolean.TRUE, events.get(1).getPayload().get("active"));
        Assert.assertTrue(skillContext.isSkillActive("skill-1"));
    }

    @Test
    public void shouldEmitSkillStepFromRestoredToolkitActiveGroup() throws Exception {
        AgentRuntimeExecutionContext context = executionContext();
        Sinks.Many<AgentRuntimeEvent> sink = Sinks.many().replay().all();
        AgentRuntimeEventBridge bridge = AgentRuntimeEventBridge.fixed(context, sink);
        AgentSkillRuntimeContext skillContext = AgentSkillRuntimeContext.from(skillBoxSpec());
        Toolkit toolkit = new Toolkit();
        skillBox(toolkit);
        toolkit.updateToolGroups(List.of("skill-1_skill_tools"), true);
        SkillExecutionObserver observer = new SkillExecutionObserver(bridge, skillContext, null);
        ReActAgent agent = initializedAgent();
        ToolUseBlock skillToolUse = ToolUseBlock.builder()
                .id("skill-step-restored")
                .name("search")
                .input(Map.of("q", "easyflow"))
                .build();
        ToolResultBlock skillToolResult = ToolResultBlock.of("skill-step-restored", "search",
                TextBlock.builder().text("done").build(), Map.of("success", true));

        observer.observe(new PreActingEvent(agent, toolkit, skillToolUse)).block();
        observer.observe(new PostActingEvent(agent, toolkit, skillToolUse, skillToolResult)).block();
        List<AgentRuntimeEvent> events = sink.asFlux().take(2).collectList().toFuture().get(3, TimeUnit.SECONDS);

        Assert.assertEquals(AgentRuntimeEventType.SKILL_STEP, events.get(0).getEventType());
        Assert.assertEquals("TOOL_CALL", events.get(0).getPayload().get("stepType"));
        Assert.assertEquals(AgentRuntimeEventType.SKILL_STEP, events.get(1).getEventType());
        Assert.assertEquals("TOOL_RESULT", events.get(1).getPayload().get("stepType"));
        Assert.assertTrue(skillContext.isSkillActive("skill-1"));
    }

    @Test
    public void shouldEmitReasoningLifecycleEvents() throws Exception {
        AgentRuntimeExecutionContext context = executionContext();
        Sinks.Many<AgentRuntimeEvent> sink = Sinks.many().replay().all();
        AgentRuntimeEventBridge bridge = AgentRuntimeEventBridge.fixed(context, sink);
        ReasoningLifecycleObserver observer = new ReasoningLifecycleObserver(bridge);
        ReActAgent agent = initializedAgent();
        Msg input = Msg.builder().role(MsgRole.USER).textContent("hello").build();
        Msg reasoning = Msg.builder().role(MsgRole.ASSISTANT).textContent("thinking done").build();

        observer.observe(new PreReasoningEvent(agent, "fake-model", null, List.of(input))).block();
        observer.observe(new PostReasoningEvent(agent, "fake-model", null, reasoning)).block();
        List<AgentRuntimeEvent> events = sink.asFlux().take(2).collectList().toFuture().get(3, TimeUnit.SECONDS);

        Assert.assertEquals(AgentRuntimeEventType.REASONING_STARTED, events.get(0).getEventType());
        Assert.assertEquals("PRE_REASONING", events.get(0).getPayload().get("phase"));
        Assert.assertEquals(AgentRuntimeEventType.REASONING_COMPLETED, events.get(1).getEventType());
        Assert.assertEquals("POST_REASONING", events.get(1).getPayload().get("phase"));
        Assert.assertEquals("thinking done", events.get(1).getPayload().get("text"));
    }

    @Test
    public void shouldEmitFailedFromRuntimeErrorObserver() throws Exception {
        AgentRuntimeExecutionContext context = executionContext();
        Sinks.Many<AgentRuntimeEvent> sink = Sinks.many().replay().all();
        AgentRuntimeEventBridge bridge = AgentRuntimeEventBridge.fixed(context, sink);
        AgentRuntimeErrorObserver observer = new AgentRuntimeErrorObserver(bridge);
        ReActAgent agent = initializedAgent();

        observer.observe(new ErrorEvent(agent, new IllegalStateException("boom"))).block();
        AgentRuntimeEvent event = sink.asFlux().take(1).collectList().toFuture().get(3, TimeUnit.SECONDS).get(0);

        Assert.assertEquals(AgentRuntimeEventType.FAILED, event.getEventType());
        Assert.assertEquals("HOOK", event.getPayload().get("source"));
        Assert.assertEquals("ERROR", event.getPayload().get("phase"));
        Assert.assertEquals(IllegalStateException.class.getName(), event.getPayload().get("errorType"));
        Assert.assertEquals("boom", event.getPayload().get("message"));
    }

    @Test
    public void shouldStreamStatefulStartedMessageAndCompletedEvents() {
        InMemoryAgentSessionStore sessionStore = new InMemoryAgentSessionStore();
        AgentInitRequest request = initRequest();
        request.setSessionStore(sessionStore);
        AgentScopeReActRuntime runtime = fakeRuntime();
        runtime.init(request);

        List<AgentRuntimeEvent> events = runtime.stream(AgentMessage.text(AgentMessageRole.USER, "hello"))
                .collectList()
                .block();

        Assert.assertFalse(events.isEmpty());
        Assert.assertEquals(AgentRuntimeEventType.STARTED, events.get(0).getEventType());
        Assert.assertTrue(events.stream().anyMatch(event -> event.getEventType() == AgentRuntimeEventType.MESSAGE_DELTA));
        String streamedText = events.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.MESSAGE_DELTA)
                .map(event -> String.valueOf(event.getPayload().getOrDefault("text", "")))
                .reduce("", String::concat);
        Assert.assertEquals("fake answer", streamedText);
        AgentRuntimeEvent completed = events.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.COMPLETED)
                .findFirst()
                .orElseThrow();
        Assert.assertEquals("fake answer", completed.getPayload().get("text"));
        Assert.assertEquals("trace-1", completed.getTraceId());
        Assert.assertEquals("session-1", completed.getSessionId());
        Assert.assertTrue(sessionStore.exists("session-1"));
    }

    /**
     * 验证增量模式会保留 URL 中连续出现的相同字符。
     */
    @Test
    public void shouldPreserveRepeatedIdenticalTextDeltas() {
        String expectedUrl = "http://127.0.0.1:39000/easyflow/file.docx";
        AgentScopeReActRuntime runtime = runtimeWithStreamingModel(List.of(
                ChatResponse.builder()
                        .id("url-response")
                        .content(List.of(TextBlock.builder().text("http://127.0.0.1:39").build()))
                        .build(),
                ChatResponse.builder()
                        .id("url-response")
                        .content(List.of(TextBlock.builder().text("0").build()))
                        .build(),
                ChatResponse.builder()
                        .id("url-response")
                        .content(List.of(TextBlock.builder().text("0").build()))
                        .build(),
                ChatResponse.builder()
                        .id("url-response")
                        .content(List.of(TextBlock.builder().text("0/easyflow/file.docx").build()))
                        .finishReason("stop")
                        .build()));
        runtime.init(initRequest());

        List<AgentRuntimeEvent> events = runtime.stream(
                        AgentMessage.text(AgentMessageRole.USER, "create file"))
                .collectList()
                .block();
        String streamedText = events.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.MESSAGE_DELTA)
                .map(event -> String.valueOf(event.getPayload().getOrDefault("text", "")))
                .reduce("", String::concat);

        Assert.assertEquals(expectedUrl, streamedText);
        AgentRuntimeEvent completed = events.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.COMPLETED)
                .findFirst()
                .orElseThrow();
        Assert.assertEquals(expectedUrl, completed.getPayload().get("text"));
    }

    @Test
    public void shouldAllowNextStreamAfterPreviousStreamCompleted() {
        AgentScopeReActRuntime runtime = fakeRuntime();
        runtime.init(initRequest());

        runtime.stream(AgentMessage.text(AgentMessageRole.USER, "first")).collectList().block();
        List<AgentRuntimeEvent> events = runtime.stream(AgentMessage.text(AgentMessageRole.USER, "second"))
                .collectList()
                .block();

        Assert.assertTrue(events.stream().anyMatch(event -> event.getEventType() == AgentRuntimeEventType.COMPLETED));
    }

    @Test
    public void shouldRejectConcurrentStatefulStream() {
        AgentScopeReActRuntime runtime = fakeRuntime();
        runtime.init(initRequest());

        reactor.core.Disposable disposable = runtime.stream(AgentMessage.text(AgentMessageRole.USER, "first"))
                .subscribe();
        try {
            runtime.stream(AgentMessage.text(AgentMessageRole.USER, "second")).collectList().block();
            Assert.fail("Concurrent stream should be rejected.");
        } catch (AgentRuntimeException expected) {
            Assert.assertTrue(expected.getMessage().contains("already streaming"));
        } finally {
            disposable.dispose();
        }
    }

    @Test
    public void shouldPersistPartialAssistantMessageWhenStreamIsCancelled() throws Exception {
        InMemoryAgentSessionStore sessionStore = new InMemoryAgentSessionStore();
        AgentInitRequest request = initRequest();
        request.setSessionStore(sessionStore);
        AgentScopeReActRuntime runtime = runtimeWithModel(List.of(
                ChatResponse.builder()
                        .id("partial-message")
                        .content(List.of(TextBlock.builder().text("partial answer").build()))
                        .finishReason("stop")
                        .build()),
                Duration.ofMillis(500));
        runtime.init(request);

        CompletableFuture<AgentRuntimeEvent> firstDelta = new CompletableFuture<>();
        reactor.core.Disposable disposable = runtime.stream(AgentMessage.text(AgentMessageRole.USER, "first"))
                .subscribe(event -> {
                    if (event.getEventType() == AgentRuntimeEventType.MESSAGE_DELTA) {
                        firstDelta.complete(event);
                    }
                }, firstDelta::completeExceptionally);
        AgentRuntimeEvent delta = firstDelta.get(3, TimeUnit.SECONDS);
        Assert.assertEquals("partial answer", delta.getPayload().get("text"));

        disposable.dispose();
        awaitCondition(() -> sessionStore.exists("session-1"));
        AgentScopeReActRuntime restoredRuntime = fakeRuntime();
        restoredRuntime.init(request);

        Assert.assertTrue(restoredRuntime.getAgent().getMemory().getMessages().stream()
                .anyMatch(message -> message.getRole() == MsgRole.ASSISTANT
                        && "partial answer".equals(message.getTextContent())));
    }

    @Test
    public void shouldNotDuplicateNormalToolEventsFromMainStream() {
        AgentInitRequest request = initRequest();
        AgentToolSpec toolSpec = new AgentToolSpec();
        toolSpec.setName("search");
        toolSpec.setDescription("search");
        request.getAgentDefinition().setToolSpecs(List.of(toolSpec));
        AtomicBoolean invoked = new AtomicBoolean(false);
        request.setToolInvokers(Map.of("search", (arguments, context) -> {
            invoked.set(true);
            return AgentToolResult.success("tool result");
        }));
        AgentScopeReActRuntime runtime = runtimeWithModel(List.of(
                ChatResponse.builder()
                        .id("tool-call-message")
                        .content(List.of(ToolUseBlock.builder()
                                .id("call-search")
                                .name("search")
                                .input(Map.of("q", "easyflow"))
                                .build()))
                        .finishReason("tool_calls")
                        .build(),
                ChatResponse.builder()
                        .id("final-message")
                        .content(List.of(TextBlock.builder().text("done").build()))
                        .finishReason("stop")
                        .build()));
        runtime.init(request);

        List<AgentRuntimeEvent> events = runtime.stream(AgentMessage.text(AgentMessageRole.USER, "use tool"))
                .collectList()
                .block();

        Assert.assertTrue(invoked.get());
        Assert.assertEquals(1, events.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.TOOL_CALL)
                .count());
        Assert.assertEquals(1, events.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.TOOL_RESULT)
                .count());
    }

    @Test
    public void shouldSuspendBeforeApprovedToolExecutionFromToolHitlInterceptor() {
        AgentInitRequest request = initRequest();
        AgentToolSpec toolSpec = new AgentToolSpec();
        toolSpec.setName("search");
        toolSpec.setDescription("search");
        toolSpec.setApprovalRequired(true);
        toolSpec.getApprovalRequest().setApprovalPrompt("Approve search?");
        toolSpec.getMetadata().put("toolDisplayName", "MCP Search - search");
        toolSpec.getMetadata().put("rawMcpToolName", "search");
        request.getAgentDefinition().setToolSpecs(List.of(toolSpec));
        AtomicBoolean invoked = new AtomicBoolean(false);
        request.setToolInvokers(Map.of("search", (arguments, context) -> {
            invoked.set(true);
            return AgentToolResult.success("tool result");
        }));
        AgentScopeReActRuntime runtime = runtimeWithModel(List.of(ChatResponse.builder()
                .id("tool-call-message")
                .content(List.of(ToolUseBlock.builder()
                        .id("call-search")
                        .name("search")
                        .input(Map.of("q", "easyflow"))
                        .build()))
                .finishReason("tool_calls")
                .build()));
        runtime.init(request);

        List<AgentRuntimeEvent> events = runtime.stream(AgentMessage.text(AgentMessageRole.USER, "use tool"))
                .collectList()
                .block();

        Assert.assertFalse(invoked.get());
        Assert.assertTrue(events.stream()
                .anyMatch(event -> event.getEventType() == AgentRuntimeEventType.TOOL_APPROVAL_REQUIRED));
        AgentRuntimeEvent approval = events.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.TOOL_APPROVAL_REQUIRED)
                .findFirst()
                .orElseThrow();
        Assert.assertEquals("MCP Search - search", approval.getPayload().get("toolDisplayName"));
        Assert.assertEquals("search", approval.getPayload().get("rawMcpToolName"));
        AgentRuntimeEvent suspended = events.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.SUSPENDED)
                .findFirst()
                .orElseThrow();
        Assert.assertEquals("TOOL_APPROVAL_REQUIRED", suspended.getPayload().get("reason"));
        Assert.assertFalse(((List<?>) suspended.getPayload().get("pendingApprovals")).isEmpty());
        Assert.assertFalse(events.stream().anyMatch(event -> event.getEventType() == AgentRuntimeEventType.COMPLETED));
        Assert.assertFalse(events.stream().anyMatch(event -> event.getEventType() == AgentRuntimeEventType.TOOL_RESULT));
        Assert.assertEquals(1, events.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.SUSPENDED)
                .count());
    }

    @Test(expected = AgentRuntimeException.class)
    public void shouldRejectResumeBeforeInit() {
        AgentResumeRequest request = new AgentResumeRequest();
        AgentResumeToken token = new AgentResumeToken();
        token.setValue("resume-token");
        request.setResumeToken(token);
        request.setApproved(true);

        fakeRuntime().resume(request).collectList().block();
    }

    @Test(expected = AgentRuntimeException.class)
    public void shouldRejectResumeWithInvalidToken() {
        AgentScopeReActRuntime runtime = fakeRuntime();
        runtime.init(initRequest());
        AgentResumeRequest request = new AgentResumeRequest();
        AgentResumeToken token = new AgentResumeToken();
        token.setValue("missing-token");
        request.setResumeToken(token);
        request.setApproved(true);

        runtime.resume(request).collectList().block();
    }

    @Test
    public void shouldResumeApprovedToolExecutionFromSuspendedRuntime() {
        InMemoryAgentSessionStore sessionStore = new InMemoryAgentSessionStore();
        AgentInitRequest request = initRequest();
        request.setSessionStore(sessionStore);
        AgentToolSpec toolSpec = new AgentToolSpec();
        toolSpec.setName("search");
        toolSpec.setDescription("search");
        toolSpec.setApprovalRequired(true);
        request.getAgentDefinition().setToolSpecs(List.of(toolSpec));
        AtomicBoolean invoked = new AtomicBoolean(false);
        request.setToolInvokers(Map.of("search", (arguments, context) -> {
            invoked.set(true);
            return AgentToolResult.success("tool result");
        }));
        AgentScopeReActRuntime runtime = runtimeWithModel(List.of(
                ChatResponse.builder()
                        .id("tool-call-message")
                        .content(List.of(ToolUseBlock.builder()
                                .id("call-search")
                                .name("search")
                                .input(Map.of("q", "easyflow"))
                                .build()))
                        .finishReason("tool_calls")
                        .build(),
                ChatResponse.builder()
                        .id("final-message")
                        .content(List.of(TextBlock.builder().text("done").build()))
                        .finishReason("stop")
                        .build()));
        runtime.init(request);
        List<AgentRuntimeEvent> suspendedEvents = runtime.stream(AgentMessage.text(AgentMessageRole.USER, "use tool"))
                .collectList()
                .block();
        AgentRuntimeEvent approval = suspendedEvents.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.TOOL_APPROVAL_REQUIRED)
                .findFirst()
                .orElseThrow();
        AgentResumeRequest resumeRequest = new AgentResumeRequest();
        AgentResumeToken token = new AgentResumeToken();
        token.setValue(String.valueOf(approval.getPayload().get("resumeToken")));
        resumeRequest.setResumeToken(token);
        resumeRequest.setApproved(true);

        List<AgentRuntimeEvent> resumeEvents = runtime.resume(resumeRequest)
                .collectList()
                .block();

        Assert.assertTrue(invoked.get());
        Assert.assertEquals(AgentRuntimeEventType.STARTED, resumeEvents.get(0).getEventType());
        Assert.assertEquals(Boolean.TRUE, resumeEvents.get(0).getPayload().get("resume"));
        Assert.assertTrue(resumeEvents.stream().anyMatch(event -> event.getEventType() == AgentRuntimeEventType.TOOL_RESULT));
        Assert.assertTrue(resumeEvents.stream().anyMatch(event -> event.getEventType() == AgentRuntimeEventType.MESSAGE_DELTA));
        Assert.assertTrue(resumeEvents.stream().anyMatch(event -> event.getEventType() == AgentRuntimeEventType.COMPLETED));
        Assert.assertFalse(resumeEvents.stream().anyMatch(event -> event.getEventType() == AgentRuntimeEventType.SUSPENDED));
        Assert.assertTrue(sessionStore.exists("session-1"));
    }

    /**
     * 验证同一轮推理包含多个审批工具时，全部批准前不会执行任何工具。
     */
    @Test
    public void shouldWaitForAllToolApprovalsBeforeExecutingBatch() {
        AgentInitRequest request = initRequest();
        AgentToolSpec searchSpec = new AgentToolSpec();
        searchSpec.setName("search");
        searchSpec.setDescription("search");
        searchSpec.setApprovalRequired(true);
        AgentToolSpec auditSpec = new AgentToolSpec();
        auditSpec.setName("audit");
        auditSpec.setDescription("audit");
        auditSpec.setApprovalRequired(true);
        request.getAgentDefinition().setToolSpecs(List.of(searchSpec, auditSpec));
        AtomicInteger invocationCount = new AtomicInteger();
        request.setToolInvokers(Map.of(
                "search", (arguments, context) -> {
                    invocationCount.incrementAndGet();
                    return AgentToolResult.success("search result");
                },
                "audit", (arguments, context) -> {
                    invocationCount.incrementAndGet();
                    return AgentToolResult.success("audit result");
                }));
        AgentScopeReActRuntime runtime = runtimeWithModel(List.of(
                ChatResponse.builder()
                        .id("tool-call-message")
                        .content(List.of(
                                ToolUseBlock.builder()
                                        .id("call-search")
                                        .name("search")
                                        .input(Map.of("q", "easyflow"))
                                        .build(),
                                ToolUseBlock.builder()
                                        .id("call-audit")
                                        .name("audit")
                                        .input(Map.of("scope", "current"))
                                        .build()))
                        .finishReason("tool_calls")
                        .build(),
                ChatResponse.builder()
                        .id("final-message")
                        .content(List.of(TextBlock.builder().text("done").build()))
                        .finishReason("stop")
                        .build()));
        runtime.init(request);

        List<AgentRuntimeEvent> initialEvents = runtime.stream(
                        AgentMessage.text(AgentMessageRole.USER, "use tools"))
                .collectList()
                .block();
        List<AgentRuntimeEvent> approvals = initialEvents.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.TOOL_APPROVAL_REQUIRED)
                .toList();

        Assert.assertEquals(2, approvals.size());
        Assert.assertEquals(1, initialEvents.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.SUSPENDED)
                .count());
        List<AgentRuntimeEvent> firstResumeEvents = runtime.resume(resumeFromApproval(approvals.get(0), true))
                .collectList()
                .block();

        Assert.assertEquals(0, invocationCount.get());
        AgentRuntimeEvent waitingEvent = firstResumeEvents.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.SUSPENDED)
                .findFirst()
                .orElseThrow();
        Assert.assertEquals(1, ((List<?>) waitingEvent.getPayload().get("pendingApprovals")).size());
        Assert.assertFalse(firstResumeEvents.stream()
                .anyMatch(event -> event.getEventType() == AgentRuntimeEventType.TOOL_CALL));

        List<AgentRuntimeEvent> secondResumeEvents = runtime.resume(resumeFromApproval(approvals.get(1), true))
                .collectList()
                .block();

        Assert.assertEquals(2, invocationCount.get());
        Assert.assertEquals(2, secondResumeEvents.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.TOOL_RESULT)
                .count());
        Assert.assertTrue(secondResumeEvents.stream()
                .anyMatch(event -> event.getEventType() == AgentRuntimeEventType.COMPLETED));
    }

    /**
     * 验证不同 toolCallId 即使名称和入参相同也会分别审批和执行。
     */
    @Test
    public void shouldPreserveDistinctApprovedToolCallsWithIdenticalInput() {
        AgentInitRequest request = initRequest();
        AgentToolSpec toolSpec = new AgentToolSpec();
        toolSpec.setName("search");
        toolSpec.setDescription("search");
        toolSpec.setApprovalRequired(true);
        request.getAgentDefinition().setToolSpecs(List.of(toolSpec));
        AtomicInteger invocationCount = new AtomicInteger();
        request.setToolInvokers(Map.of("search", (arguments, context) -> {
            invocationCount.incrementAndGet();
            return AgentToolResult.success("tool result");
        }));
        Map<String, Object> input = Map.of("q", "easyflow");
        AgentScopeReActRuntime runtime = runtimeWithModel(List.of(
                ChatResponse.builder()
                        .id("tool-call-message")
                        .content(List.of(
                                ToolUseBlock.builder()
                                        .id("call-search")
                                        .name("search")
                                        .input(input)
                                        .build(),
                                ToolUseBlock.builder()
                                        .id("call-search-duplicate")
                                        .name("search")
                                        .input(input)
                                        .build()))
                        .finishReason("tool_calls")
                        .build(),
                ChatResponse.builder()
                        .id("final-message")
                        .content(List.of(TextBlock.builder().text("done").build()))
                        .finishReason("stop")
                        .build()));
        runtime.init(request);

        List<AgentRuntimeEvent> suspendedEvents = runtime.stream(
                        AgentMessage.text(AgentMessageRole.USER, "use tool"))
                .collectList()
                .block();
        List<AgentRuntimeEvent> approvals = suspendedEvents.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.TOOL_APPROVAL_REQUIRED)
                .toList();

        Assert.assertEquals(2, approvals.size());
        List<AgentRuntimeEvent> firstResumeEvents = runtime.resume(resumeFromApproval(approvals.get(0), true))
                .collectList()
                .block();

        Assert.assertEquals(0, invocationCount.get());
        Assert.assertTrue(firstResumeEvents.stream()
                .anyMatch(event -> event.getEventType() == AgentRuntimeEventType.SUSPENDED));
        List<AgentRuntimeEvent> secondResumeEvents = runtime.resume(resumeFromApproval(approvals.get(1), true))
                .collectList()
                .block();

        Assert.assertEquals(2, invocationCount.get());
        Assert.assertEquals(2, secondResumeEvents.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.TOOL_RESULT)
                .count());
        Assert.assertTrue(secondResumeEvents.stream()
                .anyMatch(event -> event.getEventType() == AgentRuntimeEventType.COMPLETED));
    }

    /**
     * 验证相同 toolCallId 的同轮重放只审批并执行一次。
     */
    @Test
    public void shouldDeduplicateRepeatedToolCallIdWithinReasoning() {
        AgentInitRequest request = initRequest();
        AgentToolSpec toolSpec = new AgentToolSpec();
        toolSpec.setName("search");
        toolSpec.setDescription("search");
        toolSpec.setApprovalRequired(true);
        request.getAgentDefinition().setToolSpecs(List.of(toolSpec));
        AtomicInteger invocationCount = new AtomicInteger();
        request.setToolInvokers(Map.of("search", (arguments, context) -> {
            invocationCount.incrementAndGet();
            return AgentToolResult.success("tool result");
        }));
        Map<String, Object> input = Map.of("q", "easyflow");
        AgentScopeReActRuntime runtime = runtimeWithModel(List.of(
                ChatResponse.builder()
                        .id("tool-call-message")
                        .content(List.of(
                                ToolUseBlock.builder()
                                        .id("call-search")
                                        .name("search")
                                        .input(input)
                                        .build(),
                                ToolUseBlock.builder()
                                        .id("call-search")
                                        .name("search")
                                        .input(input)
                                        .build()))
                        .finishReason("tool_calls")
                        .build(),
                ChatResponse.builder()
                        .id("final-message")
                        .content(List.of(TextBlock.builder().text("done").build()))
                        .finishReason("stop")
                        .build()));
        runtime.init(request);

        List<AgentRuntimeEvent> suspendedEvents = runtime.stream(
                        AgentMessage.text(AgentMessageRole.USER, "use tool"))
                .collectList()
                .block();
        List<AgentRuntimeEvent> approvals = suspendedEvents.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.TOOL_APPROVAL_REQUIRED)
                .toList();

        Assert.assertEquals(1, approvals.size());
        List<AgentRuntimeEvent> resumeEvents = runtime.resume(resumeFromApproval(approvals.get(0), true))
                .collectList()
                .block();

        Assert.assertEquals(1, invocationCount.get());
        Assert.assertEquals(1, resumeEvents.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.TOOL_RESULT)
                .count());
        Assert.assertTrue(resumeEvents.stream()
                .anyMatch(event -> event.getEventType() == AgentRuntimeEventType.COMPLETED));
    }

    /**
     * 验证模型未提供 toolCallId 时审批链路仍会获得完整的调用身份。
     */
    @Test
    public void shouldProvideApprovalIdentityWhenModelOmitsToolCallId() {
        AgentInitRequest request = initRequest();
        AgentToolSpec toolSpec = new AgentToolSpec();
        toolSpec.setName("search");
        toolSpec.setDescription("search");
        toolSpec.setApprovalRequired(true);
        request.getAgentDefinition().setToolSpecs(List.of(toolSpec));
        request.setToolInvokers(Map.of("search", (arguments, context) ->
                AgentToolResult.success("tool result")));
        AgentScopeReActRuntime runtime = runtimeWithModel(List.of(
                ChatResponse.builder()
                        .id("tool-call-message")
                        .content(List.of(ToolUseBlock.builder()
                                .name("search")
                                .input(Map.of("q", "easyflow"))
                                .build()))
                        .finishReason("tool_calls")
                        .build(),
                ChatResponse.builder()
                        .id("final-message")
                        .content(List.of(TextBlock.builder().text("done").build()))
                        .finishReason("stop")
                        .build()));
        runtime.init(request);

        List<AgentRuntimeEvent> events = runtime.stream(
                        AgentMessage.text(AgentMessageRole.USER, "use tool"))
                .collectList()
                .block();
        AgentRuntimeEvent approval = events.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.TOOL_APPROVAL_REQUIRED)
                .findFirst()
                .orElseThrow();

        String toolCallId = String.valueOf(approval.getPayload().get("toolCallId"));
        Assert.assertFalse(toolCallId.isBlank());
        @SuppressWarnings("unchecked")
        Map<String, Object> metadata =
                (Map<String, Object>) approval.getPayload().get("approvalMetadata");
        String approvalBatchId = String.valueOf(metadata.get("approvalBatchId"));
        Assert.assertFalse(approvalBatchId.isBlank());
    }

    @Test
    public void shouldCancelRejectedToolResumeWithoutExecutingTool() {
        InMemoryAgentSessionStore sessionStore = new InMemoryAgentSessionStore();
        AgentInitRequest request = initRequest();
        request.setSessionStore(sessionStore);
        AgentToolSpec toolSpec = new AgentToolSpec();
        toolSpec.setName("search");
        toolSpec.setDescription("search");
        toolSpec.setApprovalRequired(true);
        request.getAgentDefinition().setToolSpecs(List.of(toolSpec));
        AtomicBoolean invoked = new AtomicBoolean(false);
        request.setToolInvokers(Map.of("search", (arguments, context) -> {
            invoked.set(true);
            return AgentToolResult.success("tool result");
        }));
        AgentScopeReActRuntime runtime = runtimeWithModel(List.of(ChatResponse.builder()
                .id("tool-call-message")
                .content(List.of(ToolUseBlock.builder()
                        .id("call-search")
                        .name("search")
                        .input(Map.of("q", "easyflow"))
                        .build()))
                .finishReason("tool_calls")
                .build()));
        runtime.init(request);
        List<AgentRuntimeEvent> suspendedEvents = runtime.stream(AgentMessage.text(AgentMessageRole.USER, "use tool"))
                .collectList()
                .block();
        AgentRuntimeEvent approval = suspendedEvents.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.TOOL_APPROVAL_REQUIRED)
                .findFirst()
                .orElseThrow();
        AgentResumeRequest resumeRequest = new AgentResumeRequest();
        AgentResumeToken token = new AgentResumeToken();
        token.setValue(String.valueOf(approval.getPayload().get("resumeToken")));
        resumeRequest.setResumeToken(token);
        resumeRequest.setApproved(false);
        resumeRequest.setRejectReason("not allowed");

        List<AgentRuntimeEvent> resumeEvents = runtime.resume(resumeRequest)
                .collectList()
                .block();

        Assert.assertFalse(invoked.get());
        AgentRuntimeEvent cancelled = resumeEvents.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.CANCELLED)
                .findFirst()
                .orElseThrow();
        Assert.assertEquals("not allowed", cancelled.getPayload().get("reason"));
        Assert.assertEquals(Boolean.TRUE, cancelled.getPayload().get("resume"));
        Assert.assertTrue(sessionStore.exists("session-1"));
    }

    @Test
    public void shouldRejectStreamWhileResumeIsRunning() {
        AgentInitRequest request = initRequest();
        AgentToolSpec toolSpec = new AgentToolSpec();
        toolSpec.setName("search");
        toolSpec.setDescription("search");
        toolSpec.setApprovalRequired(true);
        request.getAgentDefinition().setToolSpecs(List.of(toolSpec));
        CompletableFuture<Void> toolStarted = new CompletableFuture<>();
        request.setToolInvokers(Map.of("search", (arguments, context) -> {
            toolStarted.complete(null);
            try {
                Thread.sleep(1_000L);
            } catch (InterruptedException interruptedException) {
                Thread.currentThread().interrupt();
            }
            return AgentToolResult.success("tool result");
        }));
        AgentScopeReActRuntime runtime = runtimeWithModel(List.of(
                ChatResponse.builder()
                        .id("tool-call-message")
                        .content(List.of(ToolUseBlock.builder()
                                .id("call-search")
                                .name("search")
                                .input(Map.of("q", "easyflow"))
                                .build()))
                        .finishReason("tool_calls")
                        .build(),
                ChatResponse.builder()
                        .id("final-message")
                        .content(List.of(TextBlock.builder().text("done").build()))
                        .finishReason("stop")
                        .build()));
        runtime.init(request);
        List<AgentRuntimeEvent> suspendedEvents = runtime.stream(AgentMessage.text(AgentMessageRole.USER, "use tool"))
                .collectList()
                .block();
        AgentRuntimeEvent approval = suspendedEvents.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.TOOL_APPROVAL_REQUIRED)
                .findFirst()
                .orElseThrow();
        AgentResumeRequest resumeRequest = new AgentResumeRequest();
        AgentResumeToken token = new AgentResumeToken();
        token.setValue(String.valueOf(approval.getPayload().get("resumeToken")));
        resumeRequest.setResumeToken(token);
        resumeRequest.setApproved(true);

        reactor.core.Disposable disposable = runtime.resume(resumeRequest).subscribe();
        try {
            toolStarted.get(3, TimeUnit.SECONDS);
            runtime.stream(AgentMessage.text(AgentMessageRole.USER, "second")).collectList().block();
            Assert.fail("Concurrent stream should be rejected.");
        } catch (AgentRuntimeException expected) {
            Assert.assertTrue(expected.getMessage().contains("already streaming"));
        } catch (Exception error) {
            throw new AssertionError(error);
        } finally {
            disposable.dispose();
        }
    }

    @Test
    public void shouldAttachKnowledgeReferencesToCompletedMessage() {
        AgentInitRequest request = initRequest();
        AgentKnowledgeSpec knowledgeSpec = new AgentKnowledgeSpec();
        knowledgeSpec.setKnowledgeId("knowledge-1");
        knowledgeSpec.setName("知识库");
        request.getAgentDefinition().setKnowledgeSpecs(List.of(knowledgeSpec));
        request.setKnowledgeRetrievers(Map.of("knowledge-1", retrievalRequest -> {
            AgentKnowledgeDocument document = new AgentKnowledgeDocument();
            document.setDocumentId("doc-1");
            document.setDocumentName("说明文档");
            document.setChunkId("chunk-1");
            document.setContent("fake answer");
            document.setScore(0.9D);
            return AgentKnowledgeRetrievalResult.of(List.of(document));
        }));
        AgentScopeReActRuntime runtime = fakeRuntime();
        runtime.init(request);

        List<AgentRuntimeEvent> events = runtime.stream(AgentMessage.text(AgentMessageRole.USER, "query knowledge"))
                .collectList()
                .block();

        AgentRuntimeEvent completed = events.stream()
                .filter(event -> event.getEventType() == AgentRuntimeEventType.COMPLETED)
                .findFirst()
                .orElseThrow();
        Assert.assertNotNull(completed.getMessage());
        if (completed.getMessage().getKnowledgeReferences().isEmpty()) {
            /*
             * 当前 runtime 将知识库注册为 AgentScope AGENTIC RAG，模型需要主动调用
             * retrieve_knowledge 才会产生 KNOWLEDGE_RETRIEVAL 旁路事件。fake model
             * 不会调用该工具时，不应强行猜引用。
             */
            Assert.assertFalse(events.stream().anyMatch(event ->
                    event.getEventType() == AgentRuntimeEventType.KNOWLEDGE_RETRIEVAL));
            return;
        }
        Assert.assertEquals("chunk-1", completed.getMessage().getKnowledgeReferences().get(0).getChunkId());
    }

    private AgentScopeReActRuntime fakeRuntime() {
        return new AgentScopeReActRuntime(new FakeAgentScopeModelFactory(), new AgentScopeToolAdapter(),
                new AgentScopeKnowledgeAdapter(), new AgentScopeMemoryAdapter(), new AgentScopeSkillAdapter(),
                new AgentScopeMessageAdapter());
    }

    private AgentScopeReActRuntime runtimeWithModel(List<ChatResponse> responses) {
        return runtimeWithModel(responses, Duration.ZERO);
    }

    private AgentScopeReActRuntime runtimeWithModel(List<ChatResponse> responses, Duration completionDelay) {
        AgentScopeModelFactory modelFactory = new AgentScopeModelFactory() {
            @Override
            public Model create(AgentModelSpec modelSpec,
                                com.easyagents.agent.runtime.model.AgentGenerationOptions generationOptions) {
                return new ScriptedModel(modelSpec == null ? "fake-model" : modelSpec.getModelName(), responses, completionDelay);
            }
        };
        return new AgentScopeReActRuntime(modelFactory, new AgentScopeToolAdapter(),
                new AgentScopeKnowledgeAdapter(), new AgentScopeMemoryAdapter(), new AgentScopeSkillAdapter(),
                new AgentScopeMessageAdapter());
    }

    /**
     * 创建单次模型调用返回多个增量响应的运行时。
     *
     * @param responses 同一次模型调用中的响应增量
     * @return 测试运行时
     */
    private AgentScopeReActRuntime runtimeWithStreamingModel(List<ChatResponse> responses) {
        AgentScopeModelFactory modelFactory = new AgentScopeModelFactory() {
            @Override
            public Model create(AgentModelSpec modelSpec,
                                com.easyagents.agent.runtime.model.AgentGenerationOptions generationOptions) {
                return new StreamingScriptedModel(
                        modelSpec == null ? "fake-model" : modelSpec.getModelName(),
                        responses);
            }
        };
        return new AgentScopeReActRuntime(modelFactory, new AgentScopeToolAdapter(),
                new AgentScopeKnowledgeAdapter(), new AgentScopeMemoryAdapter(), new AgentScopeSkillAdapter(),
                new AgentScopeMessageAdapter());
    }

    /**
     * 根据审批事件创建恢复请求。
     *
     * @param approvalEvent 工具审批事件
     * @param approved 是否批准
     * @return 恢复请求
     */
    private AgentResumeRequest resumeFromApproval(AgentRuntimeEvent approvalEvent, boolean approved) {
        AgentResumeRequest request = new AgentResumeRequest();
        AgentResumeToken token = new AgentResumeToken();
        token.setValue(String.valueOf(approvalEvent.getPayload().get("resumeToken")));
        request.setResumeToken(token);
        request.setApproved(approved);
        return request;
    }

    private static class ScriptedModel implements Model {

        private final String modelName;
        private final List<ChatResponse> responses;
        private final Duration completionDelay;

        private ScriptedModel(String modelName, List<ChatResponse> responses, Duration completionDelay) {
            this.modelName = modelName;
            this.responses = responses;
            this.completionDelay = completionDelay == null ? Duration.ZERO : completionDelay;
        }

        @Override
        public Flux<ChatResponse> stream(List<Msg> messages, List<ToolSchema> toolSchemas, GenerateOptions options) {
            boolean hasToolResult = messages.stream()
                    .flatMap(message -> message.getContentBlocks(ToolResultBlock.class).stream())
                    .anyMatch(result -> "call-search".equals(result.getId()));
            List<ChatResponse> selectedResponses = hasToolResult && responses.size() > 1
                    ? responses.subList(1, responses.size())
                    : responses.subList(0, 1);
            Flux<ChatResponse> responseFlux = Flux.fromIterable(selectedResponses);
            if (completionDelay.isZero() || completionDelay.isNegative()) {
                return responseFlux;
            }
            return responseFlux.concatWith(Flux.never()).timeout(completionDelay, Flux.empty());
        }

        @Override
        public String getModelName() {
            return modelName;
        }
    }

    /**
     * 单次调用按顺序返回全部响应增量的测试模型。
     */
    private static class StreamingScriptedModel implements Model {

        private final String modelName;
        private final List<ChatResponse> responses;

        /**
         * 创建流式测试模型。
         *
         * @param modelName 模型名称
         * @param responses 响应增量
         */
        private StreamingScriptedModel(String modelName, List<ChatResponse> responses) {
            this.modelName = modelName;
            this.responses = responses;
        }

        /**
         * 返回预设的响应增量。
         *
         * @param messages 输入消息
         * @param toolSchemas 工具定义
         * @param options 生成配置
         * @return 响应流
         */
        @Override
        public Flux<ChatResponse> stream(List<Msg> messages,
                                         List<ToolSchema> toolSchemas,
                                         GenerateOptions options) {
            return Flux.fromIterable(responses);
        }

        /**
         * 获取模型名称。
         *
         * @return 模型名称
         */
        @Override
        public String getModelName() {
            return modelName;
        }
    }

    private AgentInitRequest initRequest() {
        AgentModelSpec modelSpec = new AgentModelSpec();
        modelSpec.setModelName("fake-model");
        AgentDefinition definition = new AgentDefinition();
        definition.setAgentId("agent-1");
        definition.setAgentName("agent-name");
        definition.setSystemPrompt("system");
        definition.setModelSpec(modelSpec);
        definition.setMemoryPolicy(AgentMemoryPolicy.inMemory());

        AgentInitRequest request = new AgentInitRequest();
        request.setSessionId("session-1");
        request.setSessionStore(new InMemoryAgentSessionStore());
        request.setAgentDefinition(definition);
        AgentRuntimeContext runtimeContext = new AgentRuntimeContext();
        runtimeContext.setTraceId("trace-1");
        request.setRuntimeContext(runtimeContext);
        return request;
    }

    private AgentMemorySnapshot compressionSnapshot() {
        AgentMemorySnapshot snapshot = new AgentMemorySnapshot();
        snapshot.addMessage(AgentMessage.text(AgentMessageRole.USER,
                "large previous message " + "y".repeat(80)));
        snapshot.addMessage(AgentMessage.text(AgentMessageRole.ASSISTANT,
                "old assistant answer"));
        snapshot.addMessage(AgentMessage.text(AgentMessageRole.USER, "latest user"));
        return snapshot;
    }

    private AgentSkillBoxSpec skillBoxSpec() {
        AgentSkillSpec skill = new AgentSkillSpec();
        skill.setSkillId("skill-1");
        skill.setName("Search Skill");
        skill.setDescription("Search related information with the search tool.");
        skill.setSkillContent("Use search.");
        AgentSkillBoxSpec spec = new AgentSkillBoxSpec();
        spec.setSkillBoxId("box-1");
        spec.setSkills(List.of(skill));
        spec.setToolBindings(Map.of("skill-1", List.of("search")));
        return spec;
    }

    private AgentOperateToolSpec operateToolSpec(AgentOperateToolType type) {
        AgentOperateToolSpec spec = new AgentOperateToolSpec();
        spec.setType(type);
        spec.setBaseDir(System.getProperty("java.io.tmpdir"));
        return spec;
    }

    private SkillBox skillBox(Toolkit toolkit) {
        return new AgentScopeSkillAdapter().createSkillBox(skillBoxSpec(), toolkit,
                Map.of("skill-1", List.of(new NoopAgentTool("search"))));
    }

    private record NoopAgentTool(String name) implements AgentTool {

        @Override
        public String getName() {
            return name;
        }

        @Override
        public String getDescription() {
            return name;
        }

        @Override
        public Map<String, Object> getParameters() {
            return Map.of();
        }

        @Override
        public reactor.core.publisher.Mono<ToolResultBlock> callAsync(io.agentscope.core.tool.ToolCallParam param) {
            return reactor.core.publisher.Mono.just(ToolResultBlock.text("ok"));
        }
    }

    private static class FakeMcpClientWrapper extends McpClientWrapper {

        private final AtomicBoolean closed = new AtomicBoolean(false);

        private FakeMcpClientWrapper(String name) {
            super(name);
        }

        @Override
        public Mono<Void> initialize() {
            initialized = true;
            return Mono.empty();
        }

        @Override
        public Mono<List<McpSchema.Tool>> listTools() {
            return Mono.just(List.of());
        }

        @Override
        public Mono<McpSchema.CallToolResult> callTool(String toolName, Map<String, Object> arguments) {
            return Mono.just(new McpSchema.CallToolResult(List.of(), false));
        }

        @Override
        public void close() {
            closed.set(true);
            initialized = false;
        }
    }

    private AgentRuntimeExecutionContext executionContext() {
        AgentRuntimeExecutionContext context = new AgentRuntimeExecutionContext();
        AgentDefinition definition = new AgentDefinition();
        AgentModelSpec modelSpec = new AgentModelSpec();
        modelSpec.setModelName("fake-model");
        definition.setAgentId("agent-1");
        definition.setAgentName("agent-name");
        definition.setSystemPrompt("system");
        definition.setModelSpec(modelSpec);
        definition.setMemoryPolicy(AgentMemoryPolicy.inMemory());
        context.setAgentDefinition(definition);
        context.setTraceId("trace-1");
        context.setSessionId("session-1");
        context.setRequestId("request-1");
        return context;
    }

    private ReActAgent initializedAgent() {
        AgentScopeReActRuntime runtime = fakeRuntime();
        runtime.init(initRequest());
        return runtime.getAgent();
    }

    private boolean isRuntimeHook(Hook hook) {
        return hook instanceof AgentScopeRuntimeHook;
    }

    private void awaitCondition(BooleanSupplier condition) throws Exception {
        long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3);
        while (System.nanoTime() < deadline) {
            if (condition.getAsBoolean()) {
                return;
            }
            Thread.sleep(20L);
        }
        Assert.fail("Condition was not met in time.");
    }
}
