Task configuration:
{"task_id": "23", "task_name": "set_user_edit_mode", "description": "In FreeCAD, first set the user edit mode to 3, then set it back to 0", "application_info": {"name": "FreeCAD", "executable_path": "/usr/local/bin/FreeCAD", "args": []}, "task_parameters": {"first_mode": 3, "final_mode": 0}, "instruction_template": "The application is already open. In the FreeCAD application, first set the user edit mode to ${first_mode}, then set it back to ${final_mode}", "evaluation_setup": {"scripts": [{"role": "hook", "path": "hooker.js"}, {"role": "handler", "path": "handler.py"}], "timeout": 120}, "preconditions": {"FreeCAD_running": true}, "total_key_steps": 2, "events": {"script_initialized": {"description": "Hook script initialization", "is_key_step": false}, "function_found": {"description": "Found user edit mode setting function", "is_key_step": false}, "function_called": {"description": "User edit mode setting function was called", "is_key_step": false}, "first_mode_set": {"description": "First mode setting detected", "is_key_step": true, "key_step_index": 1, "key_step_name": "Successfully set user edit mode to 3"}, "final_mode_set": {"description": "Final mode setting detected", "is_key_step": true, "key_step_index": 2, "key_step_name": "Successfully set user edit mode back to 0"}, "error": {"description": "Error event", "is_key_step": false}}, "mcp_servers": [{"command": "python3", "args": ["/home/agent/.local/share/FreeCAD/Mod/freecad_mcp/src/freecad_bridge.py"]}]}

Hook script:
// FreeCAD User Edit Mode Setting Monitoring Hook Script
// Used to monitor user edit mode setting operations in FreeCAD

(function() {
  // Script constants
  const FUNCTION_NAME = "_ZN3Gui11Application15setUserEditModeEi"
  const ORIGIN_FUNCTION_NAME = "Gui::Application::setUserEditMode"
  const FUNCTION_BEHAVIOR = "set user edit mode"

  const SCRIPT_INITIALIZED = "script_initialized"
  const FUNCTION_NOT_FOUND = "function_not_found"
  const FUNCTION_FOUND = "function_found"
  const FUNCTION_CALLED = "function_called"
  const FIRST_MODE_SET = "first_mode_set"
  const FINAL_MODE_SET = "final_mode_set"
  const ERROR = "error"
  const HOOK_INSTALLED = "hook_installed"

  const APP_NAME = "FreeCAD"
  
  // Global variables
  let funcFound = false;
  let firstModeDetected = false;
  let firstMode = 3;  // Expected first mode value
  let finalMode = 0;  // Expected final mode value
  
  // Send event to evaluation system
  function sendEvent(eventType, data = {}) {
      const payload = {
          event: eventType,
          ...data,
          timestamp: new Date().getTime()
      };
      send(payload);
  }
  
  // Find Gui::Application::setUserEditMode function
  function getFunction() {
      // Try to find directly through exported symbol
      let FuncAddr = DebugSymbol.getFunctionByName(FUNCTION_NAME);
      
      // If not found, report error
      if (!FuncAddr) {
          sendEvent(ERROR, {
              error_type: FUNCTION_NOT_FOUND,
              message: `Cannot find ${ORIGIN_FUNCTION_NAME} function`
          });
          return null;
      }
      
      // Report function found
      funcFound = true;
      sendEvent(FUNCTION_FOUND, {
          address: FuncAddr.toString(),
          message: `Found ${ORIGIN_FUNCTION_NAME} function`
      });
      
      return FuncAddr;
  }
  
  // Initialize hook and execute immediately
  function initHook() {
      sendEvent(SCRIPT_INITIALIZED, {
          message: `${APP_NAME} ${FUNCTION_BEHAVIOR} monitoring script started`
      });
      
      // Find user edit mode setting function
      const funcAddr = getFunction();
      if (!funcAddr) {
          return;
      }
      
      // Install user edit mode setting function hook
      Interceptor.attach(funcAddr, {
          onEnter: function(args) {
              try {
                  sendEvent(FUNCTION_CALLED, {
                      message: `Intercepted ${FUNCTION_BEHAVIOR} function call`
                  });
                  // args[0] is this pointer, args[1] is user edit mode value
                  this.userEditMode = parseInt(args[1]);
                  this.isFirstMode = this.userEditMode === firstMode && !firstModeDetected;
                  this.isFinalMode = this.userEditMode === finalMode && firstModeDetected;
              } catch (error) {
                  sendEvent(ERROR, {
                      error_type: "general_error",
                      message: `Execution error: ${error.message}`
                  });
              }
          },

          onLeave: function(retval) {
              try {
                  // Detect if this is the first setting of expected mode
                  if (this.isFirstMode) {
                      firstModeDetected = true;
                      sendEvent(FIRST_MODE_SET, {
                          message: `Detected first ${FUNCTION_BEHAVIOR} operation`,
                          user_edit_mode: this.userEditMode
                      });
                  }
                  // Detect if this is the final setting of expected mode
                  else if (this.isFinalMode) {
                      sendEvent(FINAL_MODE_SET, {
                          message: `Detected final ${FUNCTION_BEHAVIOR} operation`,
                          user_edit_mode: this.userEditMode
                      });
                  }
              } catch (error) {
                  sendEvent(ERROR, {
                      error_type: "general_error",
                      message: `Execution error: ${error.message}`
                  });
              }
          }
      });
      
      sendEvent(HOOK_INSTALLED, {
          message: `Hook installation complete, waiting for ${FUNCTION_BEHAVIOR} operation...`
      });
  }
  
  // Execute hook initialization immediately
  initHook();
})();


Evaluation handler:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
FreeCAD Event Handler
Responsible for processing events generated by the hook script and determining if the task is completed
"""

import os
from typing import Dict, Any, Optional, List

# 事件类型常量
SCRIPT_INITIALIZED = "script_initialized"
FUNCTION_NOT_FOUND = "function_not_found"
FUNCTION_FOUND = "function_found"
FUNCTION_CALLED = "function_called"
FIRST_MODE_SET = "first_mode_set"
FINAL_MODE_SET = "final_mode_set"
ERROR = "error"
HOOK_INSTALLED = "hook_installed"

# 关键字相关常量
USER_EDIT_MODE = "user_edit_mode"
KEY_WORDS = [USER_EDIT_MODE]

def message_handler(message: Dict[str, Any], logger: Any, task_parameter: Dict[str, Any]) -> Optional[List[Dict[str, Any]]]:
    """
    Process messages received from the hook script
    
    Args:
        message: Frida message object
        logger: Logger
        task_parameter: Task parameters
        
    Returns:
        List[Dict[str, Any]]: List of dictionaries containing status updates, or None if no updates
    """
    # Process the message
    if message.get('type') == 'send' and 'payload' in message:
        payload = message['payload']
        
        # Check if it contains an event type
        if 'event' in payload:
            event_type = payload['event']
            logger.debug(f"Event received: {event_type}")
            
            # Handle specific events
            if event_type == SCRIPT_INITIALIZED:
                logger.info(f"Hook script initialized: {payload.get('message', '')}")
                return None
                
            elif event_type == FUNCTION_FOUND:
                logger.info(f"Function found: {payload.get('address', '')}")
                return None
                
            elif event_type == FUNCTION_CALLED: 
                logger.info(f"Function called: {payload.get('message', '')}")
                return None
                
            elif event_type == FIRST_MODE_SET:
                log_info = f"Function detected first mode setting: {payload.get('message', '')}"
                for key in KEY_WORDS:
                    if key in payload:
                        log_info += f", {key}: {payload.get(key, '')}"
                logger.info(log_info)

                expected_mode = task_parameter.get("first_mode", 3)
                actual_mode = int(payload.get(USER_EDIT_MODE, -1))
                logger.debug(f"Expected mode: {expected_mode}, Actual mode: {actual_mode}")

                if actual_mode == expected_mode:
                    # Create status update list
                    updates = []
                    
                    # Report key step completed
                    updates.append({
                        'status': 'key_step',
                        'index': 1,
                        'name': f'Successfully set user edit mode to {expected_mode}'
                    })
                    
                    logger.info(f"First step completed!")
                    return updates
                
            elif event_type == FINAL_MODE_SET:
                log_info = f"Function detected final mode setting: {payload.get('message', '')}"
                for key in KEY_WORDS:
                    if key in payload:
                        log_info += f", {key}: {payload.get(key, '')}"
                logger.info(log_info)

                expected_mode = task_parameter.get("final_mode", 0)
                actual_mode = int(payload.get(USER_EDIT_MODE, -1))
                logger.debug(f"Expected mode: {expected_mode}, Actual mode: {actual_mode}")

                if actual_mode == expected_mode:
                    # Create status update list
                    updates = []
                    
                    # Report key step completed
                    updates.append({
                        'status': 'key_step',
                        'index': 2,
                        'name': f'Successfully set user edit mode back to {expected_mode}'
                    })
                    
                    # Report task success
                    updates.append({
                        'status': 'success',
                        'reason': f'Successfully completed user edit mode switch'
                    })
                    
                    logger.info(f"Task successfully completed!")
                    return updates
                
            elif event_type == ERROR:
                error_type = payload.get("error_type", "unknown")
                error_message = payload.get("message", "Unknown error")
                
                logger.error(f"Hook script error ({error_type}): {error_message}")
                
                return [{
                    'status': 'error',
                    'type': error_type,
                    'message': error_message
                }]
                
    elif message.get('type') == 'error':
        logger.error(f"Hook script error: {message.get('stack', '')}")
        
        return [{
            'status': 'error',
            'type': 'script_error',
            'message': message.get('stack', 'Unknown error')
        }]
    
    return None