Task configuration:
{"task_id": "08", "task_name": "create_rounded_rectangle", "description": "Create a rounded rectangle in FreeCAD", "application_info": {"name": "FreeCAD", "executable_path": "/usr/local/bin/FreeCAD", "args": []}, "task_parameters": {"source_path": "/FreeCAD/", "filename": "task08.FCStd", "length": 30, "width": 20, "radius": 5}, "instruction_template": "The application is already open. In FreeCAD's Part Design workbench, create a rounded rectangle with length ${length} mm, width ${width} mm, and corner radius ${radius} mm in a sketch, and save the file to ${source_path}${filename}", "evaluation_setup": {"scripts": [{"role": "hook", "path": "hooker.js"}, {"role": "handler", "path": "handler.py"}], "timeout": 240}, "preconditions": {"FreeCAD_running": true}, "total_key_steps": 2, "events": {"script_initialized": {"description": "Hook script initialized", "is_key_step": false}, "function_found": {"description": "Found document save function", "is_key_step": false}, "function_called": {"description": "Save document function called", "is_key_step": true, "key_step_index": 1, "key_step_name": "Save document"}, "function_key_word_detected": {"description": "Detected key content in the save document", "is_key_step": true, "key_step_index": 2, "key_step_name": "Rounded rectangle created and saved successfully"}, "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 create rounded rectangle monitoring hook script
// Used to listen to FreeCAD's create rounded rectangle operation and detect task completion
// After creating a rounded rectangle, save the file. The test program listens for the save and queries the corresponding document for a rounded rectangle that meets the requirements.

(function() {
  // Script constant settings
  const FUNCTION_NAME = "_ZNK3App8Document10saveToFileEPKc"
  const ORIGIN_FUNCTION_NAME = "Document::saveToFile"
  const FUNCTION_BEHAVIOR = "Save Document"

  const SCRIPT_INITIALIZED = "script_initialized"
  const FUNCTION_NOT_FOUND = "function_not_found"
  const FUNCTION_FOUND = "function_found"
  const FUNCTION_CALLED = "function_called"
  const FUNCTION_KEY_WORD_DETECTED = "function_key_word_detected"
  const ERROR = "error"
  const HOOK_INSTALLED = "hook_installed"

  const APP_NAME = "FreeCAD"
  
  // Global variable
  let funcFound = false;
  
  // Send event to the evaluation system
  function sendEvent(eventType, data = {}) {
      const payload = {
          event: eventType,
          ...data,
          timestamp: new Date().getTime()
      };
      send(payload);
  }
  
  // Find Document::saveToFile function
  function getFunction() {
      // Try to find directly through exported symbols
      let FuncAddr = DebugSymbol.getFunctionByName(FUNCTION_NAME);
      
      // If not found, report an 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 search function
      const funcAddr = getFunction();
      if (!funcAddr) {
          return;
      }
      
      // Install search function hook
      Interceptor.attach(funcAddr, {
          onEnter: function(args) {
              try {
                  sendEvent(FUNCTION_CALLED, {
                      message: `Intercepted ${FUNCTION_BEHAVIOR} function call`
                  });
                  this.filename = args[1].readCString();
              } catch (error) {
                  sendEvent(ERROR, {
                      error_type: "general_error",
                      message: `Execution error: ${error.message}`
                  });
              }
          },

          onLeave: function(retval) {
              try {
                if (retval) {
                    const pythonCode = `
import freecad
import FreeCAD
import Part

# Open the specified file
file_path = '${this.filename}'
doc = FreeCAD.open(file_path)

# Get active document
if doc is None:
    result = None
else:
    # Find shapes in the document
    rounded_rect = None
    
    # Check all objects, look for rounded rectangles
    # In Sketch, rounded rectangles are usually composed of multiple geometric elements
    for obj in doc.Objects:
        if obj.TypeId == "Sketcher::SketchObject":
            sketch = obj
            
            # Get the number of geometric figures, rounded rectangles are usually composed of straight lines and arcs
            # Simple rounded rectangles usually have 8 geometric elements: 4 straight lines and 4 arcs
            if hasattr(sketch, "Geometry") and len(sketch.Geometry) >= 8:
                # Basic properties of a rounded rectangle
                lines = [g for g in sketch.Geometry if g.TypeId == 'Part::GeomLineSegment']
                arcs = [g for g in sketch.Geometry if g.TypeId == 'Part::GeomArcOfCircle']
                
                # Simple check: rounded rectangles usually have 4 lines and 4 arcs
                if len(lines) >= 4 and len(arcs) >= 4:
                    # Simple estimation of rectangle size (calculate bounding box)
                    vertices = []
                    
                    # Get endpoints of curves
                    for line in lines:
                        vertices.append((line.StartPoint.x, line.StartPoint.y))
                        vertices.append((line.EndPoint.x, line.EndPoint.y))
                    
                    # If there are enough points to form a bounding box
                    if len(vertices) >= 4:
                        xs = [v[0] for v in vertices]
                        ys = [v[1] for v in vertices]
                        
                        # Calculate bounding box dimensions
                        length = max(xs) - min(xs)
                        width = max(ys) - min(ys)
                        
                        # Estimate radius (take the average of arc radii)
                        radius = 0
                        if arcs:
                            radius = sum([arc.Radius for arc in arcs]) / len(arcs)
                        
                        # Set result
                        rounded_rect = {
                            "length": abs(length),
                            "width": abs(width),
                            "radius": radius
                        }
                        break
    
    result = rounded_rect
                    `
                    sendEvent(FUNCTION_KEY_WORD_DETECTED, {
                        message: `Detected ${FUNCTION_BEHAVIOR} operation`,
                        filename: this.filename,
                        code: pythonCode
                    });
                }
                // Detect keyword
              } catch (error) {
                  sendEvent(ERROR, {
                      error_type: "general_error",
                      message: `Execution error: ${error.message}`
                  });
              }
          }
      });
      
      sendEvent(HOOK_INSTALLED, {
          message: `Hook installed, waiting for ${FUNCTION_BEHAVIOR} operation...`
      });
  }
  
  // Execute hook initialization immediately
  initHook();
})();

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

"""
FreeCAD rounded rectangle event handler
Handles events sent from the hook script and updates evaluation metrics
"""

from typing import Dict, Any, Optional, List

# Event type constants
SCRIPT_INITIALIZED = "script_initialized"
FUNCTION_NOT_FOUND = "function_not_found"
FUNCTION_FOUND = "function_found"
FUNCTION_CALLED = "function_called"
FUNCTION_KEY_WORD_DETECTED = "function_key_word_detected"
ERROR = "error"
HOOK_INSTALLED = "hook_installed"

# Keyword-related constants
LENGTH = "length"
WIDTH = "width"
RADIUS = "radius"

def execute_python_code(code: str, logger: Any) -> Dict[str, Any]:
    """
    Execute Python code and return result
    
    Args:
        code: Python code to execute
        logger: Logger instance
        
    Returns:
        Dict[str, Any]: Execution result
    """
    try:
        # Create a new namespace to execute the code
        namespace = {}
        exec(code, namespace)
        result = namespace.get('result', None)
        
        if result is None:
            logger.warning("Rounded rectangle object not found")
            return None
            
        # Validate result format
        required_keys = [LENGTH, WIDTH, RADIUS]
        if not all(key in result for key in required_keys):
            logger.error(f"Result is missing required keys: {required_keys}")
            return None
            
        return result
    except Exception as e:
        logger.error(f"Error while executing Python code: {str(e)}")
        return None

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 instance
        task_parameter: Task parameters
        
    Returns:
        Optional[List[Dict[str, Any]]]: Status update list, None if no updates
    """
    updates = []
    
    if message.get('type') == 'send' and 'payload' in message:
        payload = message['payload']
        
        if 'event' in payload:
            event_type = payload['event']
            logger.debug(f"Received event: {event_type}")
            
            if event_type == SCRIPT_INITIALIZED:
                logger.info(f"Hook script initialized: {payload.get('message', '')}")
                
            elif event_type == FUNCTION_FOUND:
                logger.info(f"Function found: {payload.get('address', '')}")
                
            elif event_type == FUNCTION_CALLED:
                logger.info(f"Function called: {payload.get('message', '')}")
                # Update first key step status
                updates.append({
                    'status': 'key_step',
                    'index': 1,
                    'name': 'Save document'
                })
                
            elif event_type == FUNCTION_KEY_WORD_DETECTED:
                # Execute Python code and get result
                code = payload.get('code', '')
                filename = payload.get('filename', '')
                expected_path = task_parameter.get("source_path", "") + task_parameter.get("filename", "")
                logger.info(f"Detected keyword, document path: {filename}, expected document path: {expected_path}")
                
                if filename == expected_path:
                    result = execute_python_code(code, logger)
                    if result:
                        # Check if rounded rectangle dimensions meet expectations
                        expected_length = task_parameter.get(LENGTH, 30)
                        expected_width = task_parameter.get(WIDTH, 20)
                        expected_radius = task_parameter.get(RADIUS, 5)

                        actual_length = result[LENGTH]
                        actual_width = result[WIDTH]
                        actual_radius = result[RADIUS]

                        logger.info(f"Expected dimensions: length={expected_length}, width={expected_width}, corner radius={expected_radius}")
                        logger.info(f"Actual dimensions: length={actual_length}, width={actual_width}, corner radius={actual_radius}")

                        # Allow a certain margin of error (0.01%)
                        length_error = abs((actual_length - expected_length) / expected_length) <= 0.0001
                        width_error = abs((actual_width - expected_width) / expected_width) <= 0.0001
                        radius_error = abs((actual_radius - expected_radius) / expected_radius) <= 0.0001
                        
                        if length_error and width_error and radius_error:
                            # Update second key step status
                            updates.append({
                                'status': 'key_step',
                                'index': 2,
                                'name': 'Successfully created and saved rounded rectangle'
                            })
                            
                            # Task successfully completed
                            updates.append({
                                'status': 'success',
                                'reason': 'Successfully created a rounded rectangle with required dimensions and saved'
                            })
                        else:
                            logger.warning(f"Rounded rectangle dimensions do not meet requirements: length correct: {length_error}, width correct: {width_error}, corner radius correct: {radius_error}")
                
            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}")
                
                # Record error event
                updates.append({
                    'status': 'error',
                    'type': error_type,
                    'message': error_message
                })
                
    elif message.get('type') == 'error':
        logger.error(f"Hook script error: {message.get('stack', '')}")
        
        # Record error event
        updates.append({
            'status': 'error',
            'type': 'script_error',
            'message': message.get('stack', 'Unknown error')
        })
    
    return updates if updates else None