Task configuration:
{"task_id": "07", "task_name": "create_line", "description": "Create a line in FreeCAD", "application_info": {"name": "FreeCAD", "executable_path": "/usr/local/bin/FreeCAD", "args": []}, "task_parameters": {"source_path": "/FreeCAD/", "filename": "task07.FCStd", "line_length": 50.0}, "instruction_template": "The application is already open. In FreeCAD's part design, create a line with length ${line_length} through a sketch, and save the file to ${source_path}${filename}", "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 initialized", "is_key_step": false}, "function_found": {"description": "Found document save function", "is_key_step": false}, "function_called": {"description": "Document save function was called", "is_key_step": true, "key_step_index": 1, "key_step_name": "Save document"}, "function_key_word_detected": {"description": "Detected document save key content", "is_key_step": true, "key_step_index": 2, "key_step_name": "Successfully created line and saved"}, "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 Line Creation Monitoring Hook Script
// Used to monitor FreeCAD's line creation operations

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

  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 variables
  let funcFound = false;
  
  // Send events 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 error
      if (!FuncAddr) {
          sendEvent(ERROR, {
              error_type: FUNCTION_NOT_FOUND,
              message: `Could not 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} line creation 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 math

# Open the specified file
file_path = '/FreeCAD/task07.FCStd'
doc = FreeCAD.open(file_path)

# Get active document
if doc is None:
    result = None
else:
    for obj in doc.Objects:
        # Find sketch object
        sketch = None
        if obj.TypeId == "Sketcher::SketchObject":
            sketch = obj
        if sketch is None:
            result = {
                "found": False,
                "message": "Sketch object not found"
            }
        else:
            # Check if sketch contains a line
            has_line = False
            line_length = 0.0
            
            # Iterate through geometries in the sketch
            for i in range(sketch.GeometryCount):
                geo = sketch.Geometry[i]
                if geo.TypeId == "Part::GeomLineSegment":
                    # Found a line
                    has_line = True
                    # Calculate line length
                    start = geo.StartPoint
                    end = geo.EndPoint
                    dx = end.x - start.x
                    dy = end.y - start.y
                    line_length = math.sqrt(dx*dx + dy*dy)
                    break
            
            if has_line:
                result = {
                    "found": True,
                    "has_line": True,
                    "length": line_length
                }
                break
            else:
                result = {
                    "found": True,
                    "has_line": False,
                    "message": "No line found in sketch"
            }

    print(result)
`
                    // Send keyword event containing Python code
                    sendEvent(FUNCTION_KEY_WORD_DETECTED, {
                        message: `Detected ${FUNCTION_BEHAVIOR} operation`,
                        filename: this.filename,
                        code: pythonCode
                    });
                }
                
              } catch (error) {
                  sendEvent(ERROR, {
                      error_type: "general_error",
                      message: `Execution error: ${error.message}`
                  });
              }
          }
      });
      
      sendEvent(HOOK_INSTALLED, {
          message: "Hook installation complete, waiting for line creation operation..."
      });
  }
  
  // Execute hook initialization immediately
  initHook();
})();

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

"""
FreeCAD Event Handler
Responsible for processing events from hook script and determining if the task is complete
"""

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"
FOUND = "found"
HAS_LINE = "has_line"

def execute_python_code(code: str, logger: Any) -> Dict[str, Any]:
    """
    Execute Python code and return results
    
    Args:
        code: Python code to execute
        logger: Logger
        
    Returns:
        Dict[str, Any]: Execution results
    """
    try:
        # Create a new namespace to execute code
        namespace = {}
        exec(code, namespace)
        result = namespace.get('result', None)
        
        if result is None:
            logger.warning("Line object not found")
            return None
            
        return result
    except Exception as e:
        logger.error(f"Error 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 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 there are no updates
    """
    updates = []
    
    # Process message
    if message.get('type') == 'send' and 'payload' in message:
        payload = message['payload']
        
        # Check if event type is included
        if 'event' in payload:
            event_type = payload['event']
            logger.debug(f"Received event: {event_type}")
            
            # Handle specific events
            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', '')}")
                # Saving document is the first key step
                updates.append({
                    'status': 'key_step',
                    'index': 1,
                    'name': 'Save document'
                })
                
            elif event_type == FUNCTION_KEY_WORD_DETECTED:
                # Execute Python code and get results
                code = payload.get('code', '')
                filename = payload.get('filename', '')
                logger.info(f"Keyword detected, document path: {filename}")
                
                result = execute_python_code(code, logger)
                if result:
                    # Check if sketch was created and has a line
                    if result.get(FOUND, False) and result.get(HAS_LINE, False):
                        # Check if line length matches requirements
                        expected_length = task_parameter.get('line_length', 50.0)
                        actual_length = result.get(LENGTH, 0.0)
                        
                        # Verify length meets requirements
                        if abs(actual_length - expected_length) <= 0.00001:
                            logger.info(f"Line length meets requirements: Expected {expected_length:.2f}, Actual {actual_length:.2f}")
                            
                            # Update second key step status - Line created and saved successfully
                            updates.append({
                                'status': 'key_step',
                                'index': 2,
                                'name': 'Successfully created line and saved'
                            })
                            
                            # Report task success
                            updates.append({
                                'status': 'success',
                                'reason': f'Successfully created line with length {actual_length:.2f}'
                            })
                            
                            logger.info("Task completed successfully!")
                        else:
                            logger.error(f"Line length does not meet requirements: Expected {expected_length:.2f}, Actual {actual_length:.2f}")
                            
                            updates.append({
                                'status': 'error',
                                'type': 'validation_failed',
                                'message': f'Line length does not meet requirements: Expected {expected_length:.2f}, Actual {actual_length:.2f}'
                            })
                    else:
                        if not result.get(FOUND, False):
                            logger.error("Sketch object not found")
                            updates.append({
                                'status': 'error',
                                'type': 'validation_failed',
                                'message': 'Sketch object not found'
                            })
                        elif not result.get(HAS_LINE, False):
                            logger.error("No line found in sketch")
                            updates.append({
                                'status': 'error',
                                'type': 'validation_failed',
                                'message': 'No line found in sketch'
                            })
                
            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}")
                
                updates.append({
                    'status': 'error',
                    'type': error_type,
                    'message': error_message
                })
                
    elif message.get('type') == 'error':
        logger.error(f"Hook script error: {message.get('stack', '')}")
        
        updates.append({
            'status': 'error',
            'type': 'script_error',
            'message': message.get('stack', 'Unknown error')
        })
    
    return updates if updates else None