{"repo": "MiniMax-AI/Mini-Agent", "n_pairs": 83, "version": "v2_function_scoped", "contexts": {"mini_agent/skills/document-skills/pdf/scripts/check_bounding_boxes_test.py::203": {"resolved_imports": [], "used_names": ["get_bounding_box_messages"], "enclosing_function": "test_multiple_errors_limit", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "mini_agent/skills/document-skills/pdf/scripts/check_bounding_boxes_test.py::204": {"resolved_imports": [], "used_names": ["get_bounding_box_messages"], "enclosing_function": "test_multiple_errors_limit", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "mini_agent/skills/document-skills/pdf/scripts/check_bounding_boxes_test.py::35": {"resolved_imports": [], "used_names": ["get_bounding_box_messages"], "enclosing_function": "test_no_intersections", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "mini_agent/skills/document-skills/pdf/scripts/check_bounding_boxes_test.py::36": {"resolved_imports": [], "used_names": ["get_bounding_box_messages"], "enclosing_function": "test_no_intersections", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "mini_agent/skills/document-skills/pdf/scripts/check_bounding_boxes_test.py::200": {"resolved_imports": [], "used_names": ["get_bounding_box_messages"], "enclosing_function": "test_multiple_errors_limit", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "mini_agent/skills/document-skills/pdf/scripts/check_bounding_boxes_test.py::122": {"resolved_imports": [], "used_names": ["get_bounding_box_messages"], "enclosing_function": "test_entry_height_too_small", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "mini_agent/skills/document-skills/pdf/scripts/check_bounding_boxes_test.py::53": {"resolved_imports": [], "used_names": ["get_bounding_box_messages"], "enclosing_function": "test_label_entry_intersection_same_field", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/test_acp.py::89": {"resolved_imports": ["mini_agent/acp/__init__.py", "mini_agent/config.py", "mini_agent/schema/schema.py", "mini_agent/tools/base.py"], "used_names": ["SimpleNamespace", "pytest"], "enclosing_function": "test_acp_invalid_session", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 0}, "tests/test_acp.py::78": {"resolved_imports": ["mini_agent/acp/__init__.py", "mini_agent/config.py", "mini_agent/schema/schema.py", "mini_agent/tools/base.py"], "used_names": ["SimpleNamespace", "pytest"], "enclosing_function": "test_acp_turn_executes_tool", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 0}, "tests/test_bash_tool.py::20": {"resolved_imports": ["mini_agent/tools/bash_tool.py"], "used_names": ["BashTool", "asyncio", "pytest"], "enclosing_function": "test_foreground_command", "extracted_code": "# Source: mini_agent/tools/bash_tool.py\nclass BashTool(Tool):\n \"\"\"Execute shell commands in foreground or background.\n\n Automatically detects OS and uses appropriate shell:\n - Windows: PowerShell\n - Unix/Linux/macOS: bash\n \"\"\"\n\n def __init__(self, workspace_dir: str | None = None):\n \"\"\"Initialize BashTool with OS-specific shell detection.\n\n Args:\n workspace_dir: Working directory for command execution.\n If provided, all commands run in this directory.\n If None, commands run in the process's cwd.\n \"\"\"\n self.is_windows = platform.system() == \"Windows\"\n self.shell_name = \"PowerShell\" if self.is_windows else \"bash\"\n self.workspace_dir = workspace_dir\n\n @property\n def name(self) -> str:\n return \"bash\"\n\n @property\n def description(self) -> str:\n shell_examples = {\n \"Windows\": \"\"\"Execute PowerShell commands in foreground or background.\n\nFor terminal operations like git, npm, docker, etc. DO NOT use for file operations - use specialized tools.\n\nParameters:\n - command (required): PowerShell command to execute\n - timeout (optional): Timeout in seconds (default: 120, max: 600) for foreground commands\n - run_in_background (optional): Set true for long-running commands (servers, etc.)\n\nTips:\n - Quote file paths with spaces: cd \"My Documents\"\n - Chain dependent commands with semicolon: git add . ; git commit -m \"msg\"\n - Use absolute paths instead of cd when possible\n - For background commands, monitor with bash_output and terminate with bash_kill\n\nExamples:\n - git status\n - npm test\n - python -m http.server 8080 (with run_in_background=true)\"\"\",\n \"Unix\": \"\"\"Execute bash commands in foreground or background.\n\nFor terminal operations like git, npm, docker, etc. DO NOT use for file operations - use specialized tools.\n\nParameters:\n - command (required): Bash command to execute\n - timeout (optional): Timeout in seconds (default: 120, max: 600) for foreground commands\n - run_in_background (optional): Set true for long-running commands (servers, etc.)\n\nTips:\n - Quote file paths with spaces: cd \"My Documents\"\n - Chain dependent commands with &&: git add . && git commit -m \"msg\"\n - Use absolute paths instead of cd when possible\n - For background commands, monitor with bash_output and terminate with bash_kill\n\nExamples:\n - git status\n - npm test\n - python3 -m http.server 8080 (with run_in_background=true)\"\"\",\n }\n return shell_examples[\"Windows\"] if self.is_windows else shell_examples[\"Unix\"]\n\n @property\n def parameters(self) -> dict[str, Any]:\n cmd_desc = f\"The {self.shell_name} command to execute. Quote file paths with spaces using double quotes.\"\n return {\n \"type\": \"object\",\n \"properties\": {\n \"command\": {\n \"type\": \"string\",\n \"description\": cmd_desc,\n },\n \"timeout\": {\n \"type\": \"integer\",\n \"description\": \"Optional: Timeout in seconds (default: 120, max: 600). Only applies to foreground commands.\",\n \"default\": 120,\n },\n \"run_in_background\": {\n \"type\": \"boolean\",\n \"description\": \"Optional: Set to true to run the command in the background. Use this for long-running commands like servers. You can monitor output using bash_output tool.\",\n \"default\": False,\n },\n },\n \"required\": [\"command\"],\n }\n\n async def execute(\n self,\n command: str,\n timeout: int = 120,\n run_in_background: bool = False,\n ) -> ToolResult:\n \"\"\"Execute shell command with optional background execution.\n\n Args:\n command: The shell command to execute\n timeout: Timeout in seconds (default: 120, max: 600)\n run_in_background: Set true to run command in background\n\n Returns:\n BashExecutionResult with command output and status\n \"\"\"\n\n try:\n # Validate timeout\n if timeout > 600:\n timeout = 600\n elif timeout < 1:\n timeout = 120\n\n # Prepare shell-specific command execution\n if self.is_windows:\n # Windows: Use PowerShell with appropriate encoding\n shell_cmd = [\"powershell.exe\", \"-NoProfile\", \"-Command\", command]\n else:\n # Unix/Linux/macOS: Use bash\n shell_cmd = command\n\n if run_in_background:\n # Background execution: Create isolated process\n bash_id = str(uuid.uuid4())[:8]\n\n # Start background process with combined stdout/stderr\n if self.is_windows:\n process = await asyncio.create_subprocess_exec(\n *shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.STDOUT,\n cwd=self.workspace_dir,\n )\n else:\n process = await asyncio.create_subprocess_shell(\n shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.STDOUT,\n cwd=self.workspace_dir,\n )\n\n # Create background shell and add to manager\n bg_shell = BackgroundShell(bash_id=bash_id, command=command, process=process, start_time=time.time())\n BackgroundShellManager.add(bg_shell)\n\n # Start monitoring task\n await BackgroundShellManager.start_monitor(bash_id)\n\n # Return immediately with bash_id\n message = f\"Command started in background. Use bash_output to monitor (bash_id='{bash_id}').\"\n formatted_content = f\"{message}\\n\\nCommand: {command}\\nBash ID: {bash_id}\"\n\n return BashOutputResult(\n success=True,\n content=formatted_content,\n stdout=f\"Background command started with ID: {bash_id}\",\n stderr=\"\",\n exit_code=0,\n bash_id=bash_id,\n )\n\n else:\n # Foreground execution: Create isolated process\n if self.is_windows:\n process = await asyncio.create_subprocess_exec(\n *shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n cwd=self.workspace_dir,\n )\n else:\n process = await asyncio.create_subprocess_shell(\n shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n cwd=self.workspace_dir,\n )\n\n try:\n stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)\n except asyncio.TimeoutError:\n process.kill()\n error_msg = f\"Command timed out after {timeout} seconds\"\n return BashOutputResult(\n success=False,\n error=error_msg,\n stdout=\"\",\n stderr=error_msg,\n exit_code=-1,\n )\n\n # Decode output\n stdout_text = stdout.decode(\"utf-8\", errors=\"replace\")\n stderr_text = stderr.decode(\"utf-8\", errors=\"replace\")\n\n # Create result (content auto-formatted by model_validator)\n is_success = process.returncode == 0\n error_msg = None\n if not is_success:\n error_msg = f\"Command failed with exit code {process.returncode}\"\n if stderr_text:\n error_msg += f\"\\n{stderr_text.strip()}\"\n\n return BashOutputResult(\n success=is_success,\n error=error_msg,\n stdout=stdout_text,\n stderr=stderr_text,\n exit_code=process.returncode or 0,\n )\n\n except Exception as e:\n return BashOutputResult(\n success=False,\n error=str(e),\n stdout=\"\",\n stderr=str(e),\n exit_code=-1,\n )", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 8734}, "tests/test_bash_tool.py::63": {"resolved_imports": ["mini_agent/tools/bash_tool.py"], "used_names": ["BashTool", "asyncio", "pytest"], "enclosing_function": "test_command_timeout", "extracted_code": "# Source: mini_agent/tools/bash_tool.py\nclass BashTool(Tool):\n \"\"\"Execute shell commands in foreground or background.\n\n Automatically detects OS and uses appropriate shell:\n - Windows: PowerShell\n - Unix/Linux/macOS: bash\n \"\"\"\n\n def __init__(self, workspace_dir: str | None = None):\n \"\"\"Initialize BashTool with OS-specific shell detection.\n\n Args:\n workspace_dir: Working directory for command execution.\n If provided, all commands run in this directory.\n If None, commands run in the process's cwd.\n \"\"\"\n self.is_windows = platform.system() == \"Windows\"\n self.shell_name = \"PowerShell\" if self.is_windows else \"bash\"\n self.workspace_dir = workspace_dir\n\n @property\n def name(self) -> str:\n return \"bash\"\n\n @property\n def description(self) -> str:\n shell_examples = {\n \"Windows\": \"\"\"Execute PowerShell commands in foreground or background.\n\nFor terminal operations like git, npm, docker, etc. DO NOT use for file operations - use specialized tools.\n\nParameters:\n - command (required): PowerShell command to execute\n - timeout (optional): Timeout in seconds (default: 120, max: 600) for foreground commands\n - run_in_background (optional): Set true for long-running commands (servers, etc.)\n\nTips:\n - Quote file paths with spaces: cd \"My Documents\"\n - Chain dependent commands with semicolon: git add . ; git commit -m \"msg\"\n - Use absolute paths instead of cd when possible\n - For background commands, monitor with bash_output and terminate with bash_kill\n\nExamples:\n - git status\n - npm test\n - python -m http.server 8080 (with run_in_background=true)\"\"\",\n \"Unix\": \"\"\"Execute bash commands in foreground or background.\n\nFor terminal operations like git, npm, docker, etc. DO NOT use for file operations - use specialized tools.\n\nParameters:\n - command (required): Bash command to execute\n - timeout (optional): Timeout in seconds (default: 120, max: 600) for foreground commands\n - run_in_background (optional): Set true for long-running commands (servers, etc.)\n\nTips:\n - Quote file paths with spaces: cd \"My Documents\"\n - Chain dependent commands with &&: git add . && git commit -m \"msg\"\n - Use absolute paths instead of cd when possible\n - For background commands, monitor with bash_output and terminate with bash_kill\n\nExamples:\n - git status\n - npm test\n - python3 -m http.server 8080 (with run_in_background=true)\"\"\",\n }\n return shell_examples[\"Windows\"] if self.is_windows else shell_examples[\"Unix\"]\n\n @property\n def parameters(self) -> dict[str, Any]:\n cmd_desc = f\"The {self.shell_name} command to execute. Quote file paths with spaces using double quotes.\"\n return {\n \"type\": \"object\",\n \"properties\": {\n \"command\": {\n \"type\": \"string\",\n \"description\": cmd_desc,\n },\n \"timeout\": {\n \"type\": \"integer\",\n \"description\": \"Optional: Timeout in seconds (default: 120, max: 600). Only applies to foreground commands.\",\n \"default\": 120,\n },\n \"run_in_background\": {\n \"type\": \"boolean\",\n \"description\": \"Optional: Set to true to run the command in the background. Use this for long-running commands like servers. You can monitor output using bash_output tool.\",\n \"default\": False,\n },\n },\n \"required\": [\"command\"],\n }\n\n async def execute(\n self,\n command: str,\n timeout: int = 120,\n run_in_background: bool = False,\n ) -> ToolResult:\n \"\"\"Execute shell command with optional background execution.\n\n Args:\n command: The shell command to execute\n timeout: Timeout in seconds (default: 120, max: 600)\n run_in_background: Set true to run command in background\n\n Returns:\n BashExecutionResult with command output and status\n \"\"\"\n\n try:\n # Validate timeout\n if timeout > 600:\n timeout = 600\n elif timeout < 1:\n timeout = 120\n\n # Prepare shell-specific command execution\n if self.is_windows:\n # Windows: Use PowerShell with appropriate encoding\n shell_cmd = [\"powershell.exe\", \"-NoProfile\", \"-Command\", command]\n else:\n # Unix/Linux/macOS: Use bash\n shell_cmd = command\n\n if run_in_background:\n # Background execution: Create isolated process\n bash_id = str(uuid.uuid4())[:8]\n\n # Start background process with combined stdout/stderr\n if self.is_windows:\n process = await asyncio.create_subprocess_exec(\n *shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.STDOUT,\n cwd=self.workspace_dir,\n )\n else:\n process = await asyncio.create_subprocess_shell(\n shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.STDOUT,\n cwd=self.workspace_dir,\n )\n\n # Create background shell and add to manager\n bg_shell = BackgroundShell(bash_id=bash_id, command=command, process=process, start_time=time.time())\n BackgroundShellManager.add(bg_shell)\n\n # Start monitoring task\n await BackgroundShellManager.start_monitor(bash_id)\n\n # Return immediately with bash_id\n message = f\"Command started in background. Use bash_output to monitor (bash_id='{bash_id}').\"\n formatted_content = f\"{message}\\n\\nCommand: {command}\\nBash ID: {bash_id}\"\n\n return BashOutputResult(\n success=True,\n content=formatted_content,\n stdout=f\"Background command started with ID: {bash_id}\",\n stderr=\"\",\n exit_code=0,\n bash_id=bash_id,\n )\n\n else:\n # Foreground execution: Create isolated process\n if self.is_windows:\n process = await asyncio.create_subprocess_exec(\n *shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n cwd=self.workspace_dir,\n )\n else:\n process = await asyncio.create_subprocess_shell(\n shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n cwd=self.workspace_dir,\n )\n\n try:\n stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)\n except asyncio.TimeoutError:\n process.kill()\n error_msg = f\"Command timed out after {timeout} seconds\"\n return BashOutputResult(\n success=False,\n error=error_msg,\n stdout=\"\",\n stderr=error_msg,\n exit_code=-1,\n )\n\n # Decode output\n stdout_text = stdout.decode(\"utf-8\", errors=\"replace\")\n stderr_text = stderr.decode(\"utf-8\", errors=\"replace\")\n\n # Create result (content auto-formatted by model_validator)\n is_success = process.returncode == 0\n error_msg = None\n if not is_success:\n error_msg = f\"Command failed with exit code {process.returncode}\"\n if stderr_text:\n error_msg += f\"\\n{stderr_text.strip()}\"\n\n return BashOutputResult(\n success=is_success,\n error=error_msg,\n stdout=stdout_text,\n stderr=stderr_text,\n exit_code=process.returncode or 0,\n )\n\n except Exception as e:\n return BashOutputResult(\n success=False,\n error=str(e),\n stdout=\"\",\n stderr=str(e),\n exit_code=-1,\n )", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 8734}, "tests/test_bash_tool.py::49": {"resolved_imports": ["mini_agent/tools/bash_tool.py"], "used_names": ["BashTool", "asyncio", "pytest"], "enclosing_function": "test_command_failure", "extracted_code": "# Source: mini_agent/tools/bash_tool.py\nclass BashTool(Tool):\n \"\"\"Execute shell commands in foreground or background.\n\n Automatically detects OS and uses appropriate shell:\n - Windows: PowerShell\n - Unix/Linux/macOS: bash\n \"\"\"\n\n def __init__(self, workspace_dir: str | None = None):\n \"\"\"Initialize BashTool with OS-specific shell detection.\n\n Args:\n workspace_dir: Working directory for command execution.\n If provided, all commands run in this directory.\n If None, commands run in the process's cwd.\n \"\"\"\n self.is_windows = platform.system() == \"Windows\"\n self.shell_name = \"PowerShell\" if self.is_windows else \"bash\"\n self.workspace_dir = workspace_dir\n\n @property\n def name(self) -> str:\n return \"bash\"\n\n @property\n def description(self) -> str:\n shell_examples = {\n \"Windows\": \"\"\"Execute PowerShell commands in foreground or background.\n\nFor terminal operations like git, npm, docker, etc. DO NOT use for file operations - use specialized tools.\n\nParameters:\n - command (required): PowerShell command to execute\n - timeout (optional): Timeout in seconds (default: 120, max: 600) for foreground commands\n - run_in_background (optional): Set true for long-running commands (servers, etc.)\n\nTips:\n - Quote file paths with spaces: cd \"My Documents\"\n - Chain dependent commands with semicolon: git add . ; git commit -m \"msg\"\n - Use absolute paths instead of cd when possible\n - For background commands, monitor with bash_output and terminate with bash_kill\n\nExamples:\n - git status\n - npm test\n - python -m http.server 8080 (with run_in_background=true)\"\"\",\n \"Unix\": \"\"\"Execute bash commands in foreground or background.\n\nFor terminal operations like git, npm, docker, etc. DO NOT use for file operations - use specialized tools.\n\nParameters:\n - command (required): Bash command to execute\n - timeout (optional): Timeout in seconds (default: 120, max: 600) for foreground commands\n - run_in_background (optional): Set true for long-running commands (servers, etc.)\n\nTips:\n - Quote file paths with spaces: cd \"My Documents\"\n - Chain dependent commands with &&: git add . && git commit -m \"msg\"\n - Use absolute paths instead of cd when possible\n - For background commands, monitor with bash_output and terminate with bash_kill\n\nExamples:\n - git status\n - npm test\n - python3 -m http.server 8080 (with run_in_background=true)\"\"\",\n }\n return shell_examples[\"Windows\"] if self.is_windows else shell_examples[\"Unix\"]\n\n @property\n def parameters(self) -> dict[str, Any]:\n cmd_desc = f\"The {self.shell_name} command to execute. Quote file paths with spaces using double quotes.\"\n return {\n \"type\": \"object\",\n \"properties\": {\n \"command\": {\n \"type\": \"string\",\n \"description\": cmd_desc,\n },\n \"timeout\": {\n \"type\": \"integer\",\n \"description\": \"Optional: Timeout in seconds (default: 120, max: 600). Only applies to foreground commands.\",\n \"default\": 120,\n },\n \"run_in_background\": {\n \"type\": \"boolean\",\n \"description\": \"Optional: Set to true to run the command in the background. Use this for long-running commands like servers. You can monitor output using bash_output tool.\",\n \"default\": False,\n },\n },\n \"required\": [\"command\"],\n }\n\n async def execute(\n self,\n command: str,\n timeout: int = 120,\n run_in_background: bool = False,\n ) -> ToolResult:\n \"\"\"Execute shell command with optional background execution.\n\n Args:\n command: The shell command to execute\n timeout: Timeout in seconds (default: 120, max: 600)\n run_in_background: Set true to run command in background\n\n Returns:\n BashExecutionResult with command output and status\n \"\"\"\n\n try:\n # Validate timeout\n if timeout > 600:\n timeout = 600\n elif timeout < 1:\n timeout = 120\n\n # Prepare shell-specific command execution\n if self.is_windows:\n # Windows: Use PowerShell with appropriate encoding\n shell_cmd = [\"powershell.exe\", \"-NoProfile\", \"-Command\", command]\n else:\n # Unix/Linux/macOS: Use bash\n shell_cmd = command\n\n if run_in_background:\n # Background execution: Create isolated process\n bash_id = str(uuid.uuid4())[:8]\n\n # Start background process with combined stdout/stderr\n if self.is_windows:\n process = await asyncio.create_subprocess_exec(\n *shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.STDOUT,\n cwd=self.workspace_dir,\n )\n else:\n process = await asyncio.create_subprocess_shell(\n shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.STDOUT,\n cwd=self.workspace_dir,\n )\n\n # Create background shell and add to manager\n bg_shell = BackgroundShell(bash_id=bash_id, command=command, process=process, start_time=time.time())\n BackgroundShellManager.add(bg_shell)\n\n # Start monitoring task\n await BackgroundShellManager.start_monitor(bash_id)\n\n # Return immediately with bash_id\n message = f\"Command started in background. Use bash_output to monitor (bash_id='{bash_id}').\"\n formatted_content = f\"{message}\\n\\nCommand: {command}\\nBash ID: {bash_id}\"\n\n return BashOutputResult(\n success=True,\n content=formatted_content,\n stdout=f\"Background command started with ID: {bash_id}\",\n stderr=\"\",\n exit_code=0,\n bash_id=bash_id,\n )\n\n else:\n # Foreground execution: Create isolated process\n if self.is_windows:\n process = await asyncio.create_subprocess_exec(\n *shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n cwd=self.workspace_dir,\n )\n else:\n process = await asyncio.create_subprocess_shell(\n shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n cwd=self.workspace_dir,\n )\n\n try:\n stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)\n except asyncio.TimeoutError:\n process.kill()\n error_msg = f\"Command timed out after {timeout} seconds\"\n return BashOutputResult(\n success=False,\n error=error_msg,\n stdout=\"\",\n stderr=error_msg,\n exit_code=-1,\n )\n\n # Decode output\n stdout_text = stdout.decode(\"utf-8\", errors=\"replace\")\n stderr_text = stderr.decode(\"utf-8\", errors=\"replace\")\n\n # Create result (content auto-formatted by model_validator)\n is_success = process.returncode == 0\n error_msg = None\n if not is_success:\n error_msg = f\"Command failed with exit code {process.returncode}\"\n if stderr_text:\n error_msg += f\"\\n{stderr_text.strip()}\"\n\n return BashOutputResult(\n success=is_success,\n error=error_msg,\n stdout=stdout_text,\n stderr=stderr_text,\n exit_code=process.returncode or 0,\n )\n\n except Exception as e:\n return BashOutputResult(\n success=False,\n error=str(e),\n stdout=\"\",\n stderr=str(e),\n exit_code=-1,\n )", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 8734}, "tests/test_bash_tool.py::181": {"resolved_imports": ["mini_agent/tools/bash_tool.py"], "used_names": ["BackgroundShellManager", "BashKillTool", "BashTool", "asyncio", "pytest"], "enclosing_function": "test_bash_kill", "extracted_code": "# Source: mini_agent/tools/bash_tool.py\nclass BackgroundShellManager:\n \"\"\"Manager for all background shell processes.\"\"\"\n\n _shells: dict[str, BackgroundShell] = {}\n _monitor_tasks: dict[str, asyncio.Task] = {}\n\n @classmethod\n def add(cls, shell: BackgroundShell) -> None:\n \"\"\"Add a background shell to management.\"\"\"\n cls._shells[shell.bash_id] = shell\n\n @classmethod\n def get(cls, bash_id: str) -> BackgroundShell | None:\n \"\"\"Get a background shell by ID.\"\"\"\n return cls._shells.get(bash_id)\n\n @classmethod\n def get_available_ids(cls) -> list[str]:\n \"\"\"Get all available bash IDs.\"\"\"\n return list(cls._shells.keys())\n\n @classmethod\n def _remove(cls, bash_id: str) -> None:\n \"\"\"Remove a background shell from management (internal use only).\"\"\"\n if bash_id in cls._shells:\n del cls._shells[bash_id]\n\n @classmethod\n async def start_monitor(cls, bash_id: str) -> None:\n \"\"\"Start monitoring a background shell's output.\"\"\"\n shell = cls.get(bash_id)\n if not shell:\n return\n\n async def monitor():\n try:\n process = shell.process\n # Continuously read output until process ends\n while process.returncode is None:\n try:\n if process.stdout:\n line = await asyncio.wait_for(process.stdout.readline(), timeout=0.1)\n if line:\n decoded_line = line.decode(\"utf-8\", errors=\"replace\").rstrip(\"\\n\")\n shell.add_output(decoded_line)\n else:\n break\n except asyncio.TimeoutError:\n await asyncio.sleep(0.1)\n continue\n except Exception:\n await asyncio.sleep(0.1)\n continue\n\n # Process ended, wait for exit code\n try:\n returncode = await process.wait()\n except Exception:\n returncode = -1\n\n shell.update_status(is_alive=False, exit_code=returncode)\n\n except Exception as e:\n if bash_id in cls._shells:\n cls._shells[bash_id].status = \"error\"\n cls._shells[bash_id].add_output(f\"Monitor error: {str(e)}\")\n finally:\n if bash_id in cls._monitor_tasks:\n del cls._monitor_tasks[bash_id]\n\n task = asyncio.create_task(monitor())\n cls._monitor_tasks[bash_id] = task\n\n @classmethod\n def _cancel_monitor(cls, bash_id: str) -> None:\n \"\"\"Cancel and remove a monitoring task (internal use only).\"\"\"\n if bash_id in cls._monitor_tasks:\n task = cls._monitor_tasks[bash_id]\n if not task.done():\n task.cancel()\n del cls._monitor_tasks[bash_id]\n\n @classmethod\n async def terminate(cls, bash_id: str) -> BackgroundShell:\n \"\"\"Terminate a background shell and clean up all resources.\n\n Args:\n bash_id: The unique identifier of the background shell\n\n Returns:\n The terminated BackgroundShell object\n\n Raises:\n ValueError: If shell not found\n \"\"\"\n shell = cls.get(bash_id)\n if not shell:\n raise ValueError(f\"Shell not found: {bash_id}\")\n\n # Terminate the process\n await shell.terminate()\n\n # Clean up monitoring and remove from manager\n cls._cancel_monitor(bash_id)\n cls._remove(bash_id)\n\n return shell\n\nclass BashTool(Tool):\n \"\"\"Execute shell commands in foreground or background.\n\n Automatically detects OS and uses appropriate shell:\n - Windows: PowerShell\n - Unix/Linux/macOS: bash\n \"\"\"\n\n def __init__(self, workspace_dir: str | None = None):\n \"\"\"Initialize BashTool with OS-specific shell detection.\n\n Args:\n workspace_dir: Working directory for command execution.\n If provided, all commands run in this directory.\n If None, commands run in the process's cwd.\n \"\"\"\n self.is_windows = platform.system() == \"Windows\"\n self.shell_name = \"PowerShell\" if self.is_windows else \"bash\"\n self.workspace_dir = workspace_dir\n\n @property\n def name(self) -> str:\n return \"bash\"\n\n @property\n def description(self) -> str:\n shell_examples = {\n \"Windows\": \"\"\"Execute PowerShell commands in foreground or background.\n\nFor terminal operations like git, npm, docker, etc. DO NOT use for file operations - use specialized tools.\n\nParameters:\n - command (required): PowerShell command to execute\n - timeout (optional): Timeout in seconds (default: 120, max: 600) for foreground commands\n - run_in_background (optional): Set true for long-running commands (servers, etc.)\n\nTips:\n - Quote file paths with spaces: cd \"My Documents\"\n - Chain dependent commands with semicolon: git add . ; git commit -m \"msg\"\n - Use absolute paths instead of cd when possible\n - For background commands, monitor with bash_output and terminate with bash_kill\n\nExamples:\n - git status\n - npm test\n - python -m http.server 8080 (with run_in_background=true)\"\"\",\n \"Unix\": \"\"\"Execute bash commands in foreground or background.\n\nFor terminal operations like git, npm, docker, etc. DO NOT use for file operations - use specialized tools.\n\nParameters:\n - command (required): Bash command to execute\n - timeout (optional): Timeout in seconds (default: 120, max: 600) for foreground commands\n - run_in_background (optional): Set true for long-running commands (servers, etc.)\n\nTips:\n - Quote file paths with spaces: cd \"My Documents\"\n - Chain dependent commands with &&: git add . && git commit -m \"msg\"\n - Use absolute paths instead of cd when possible\n - For background commands, monitor with bash_output and terminate with bash_kill\n\nExamples:\n - git status\n - npm test\n - python3 -m http.server 8080 (with run_in_background=true)\"\"\",\n }\n return shell_examples[\"Windows\"] if self.is_windows else shell_examples[\"Unix\"]\n\n @property\n def parameters(self) -> dict[str, Any]:\n cmd_desc = f\"The {self.shell_name} command to execute. Quote file paths with spaces using double quotes.\"\n return {\n \"type\": \"object\",\n \"properties\": {\n \"command\": {\n \"type\": \"string\",\n \"description\": cmd_desc,\n },\n \"timeout\": {\n \"type\": \"integer\",\n \"description\": \"Optional: Timeout in seconds (default: 120, max: 600). Only applies to foreground commands.\",\n \"default\": 120,\n },\n \"run_in_background\": {\n \"type\": \"boolean\",\n \"description\": \"Optional: Set to true to run the command in the background. Use this for long-running commands like servers. You can monitor output using bash_output tool.\",\n \"default\": False,\n },\n },\n \"required\": [\"command\"],\n }\n\n async def execute(\n self,\n command: str,\n timeout: int = 120,\n run_in_background: bool = False,\n ) -> ToolResult:\n \"\"\"Execute shell command with optional background execution.\n\n Args:\n command: The shell command to execute\n timeout: Timeout in seconds (default: 120, max: 600)\n run_in_background: Set true to run command in background\n\n Returns:\n BashExecutionResult with command output and status\n \"\"\"\n\n try:\n # Validate timeout\n if timeout > 600:\n timeout = 600\n elif timeout < 1:\n timeout = 120\n\n # Prepare shell-specific command execution\n if self.is_windows:\n # Windows: Use PowerShell with appropriate encoding\n shell_cmd = [\"powershell.exe\", \"-NoProfile\", \"-Command\", command]\n else:\n # Unix/Linux/macOS: Use bash\n shell_cmd = command\n\n if run_in_background:\n # Background execution: Create isolated process\n bash_id = str(uuid.uuid4())[:8]\n\n # Start background process with combined stdout/stderr\n if self.is_windows:\n process = await asyncio.create_subprocess_exec(\n *shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.STDOUT,\n cwd=self.workspace_dir,\n )\n else:\n process = await asyncio.create_subprocess_shell(\n shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.STDOUT,\n cwd=self.workspace_dir,\n )\n\n # Create background shell and add to manager\n bg_shell = BackgroundShell(bash_id=bash_id, command=command, process=process, start_time=time.time())\n BackgroundShellManager.add(bg_shell)\n\n # Start monitoring task\n await BackgroundShellManager.start_monitor(bash_id)\n\n # Return immediately with bash_id\n message = f\"Command started in background. Use bash_output to monitor (bash_id='{bash_id}').\"\n formatted_content = f\"{message}\\n\\nCommand: {command}\\nBash ID: {bash_id}\"\n\n return BashOutputResult(\n success=True,\n content=formatted_content,\n stdout=f\"Background command started with ID: {bash_id}\",\n stderr=\"\",\n exit_code=0,\n bash_id=bash_id,\n )\n\n else:\n # Foreground execution: Create isolated process\n if self.is_windows:\n process = await asyncio.create_subprocess_exec(\n *shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n cwd=self.workspace_dir,\n )\n else:\n process = await asyncio.create_subprocess_shell(\n shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n cwd=self.workspace_dir,\n )\n\n try:\n stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)\n except asyncio.TimeoutError:\n process.kill()\n error_msg = f\"Command timed out after {timeout} seconds\"\n return BashOutputResult(\n success=False,\n error=error_msg,\n stdout=\"\",\n stderr=error_msg,\n exit_code=-1,\n )\n\n # Decode output\n stdout_text = stdout.decode(\"utf-8\", errors=\"replace\")\n stderr_text = stderr.decode(\"utf-8\", errors=\"replace\")\n\n # Create result (content auto-formatted by model_validator)\n is_success = process.returncode == 0\n error_msg = None\n if not is_success:\n error_msg = f\"Command failed with exit code {process.returncode}\"\n if stderr_text:\n error_msg += f\"\\n{stderr_text.strip()}\"\n\n return BashOutputResult(\n success=is_success,\n error=error_msg,\n stdout=stdout_text,\n stderr=stderr_text,\n exit_code=process.returncode or 0,\n )\n\n except Exception as e:\n return BashOutputResult(\n success=False,\n error=str(e),\n stdout=\"\",\n stderr=str(e),\n exit_code=-1,\n )\n\nclass BashKillTool(Tool):\n \"\"\"Terminate a running background bash shell.\"\"\"\n\n @property\n def name(self) -> str:\n return \"bash_kill\"\n\n @property\n def description(self) -> str:\n return \"\"\"Kills a running background bash shell by its ID.\n\n - Takes a bash_id parameter identifying the shell to kill\n - Attempts graceful termination (SIGTERM) first, then forces (SIGKILL) if needed\n - Returns the final status and any remaining output before termination\n - Cleans up all resources associated with the shell\n - Use this tool when you need to terminate a long-running shell\n - Shell IDs can be found using the bash tool with run_in_background=true\n\n Example: bash_kill(bash_id=\"abc12345\")\"\"\"\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"bash_id\": {\n \"type\": \"string\",\n \"description\": \"The ID of the background shell to terminate. Shell IDs are returned when starting a command with run_in_background=true.\",\n },\n },\n \"required\": [\"bash_id\"],\n }\n\n async def execute(self, bash_id: str) -> BashOutputResult:\n \"\"\"Terminate a background shell process.\n\n Args:\n bash_id: The unique identifier of the background shell to terminate\n\n Returns:\n BashOutputResult with termination status and remaining output\n \"\"\"\n\n try:\n # Get remaining output before termination\n bg_shell = BackgroundShellManager.get(bash_id)\n if bg_shell:\n remaining_lines = bg_shell.get_new_output()\n else:\n remaining_lines = []\n\n # Terminate through manager (handles all cleanup)\n bg_shell = await BackgroundShellManager.terminate(bash_id)\n\n # Get remaining output\n stdout = \"\\n\".join(remaining_lines) if remaining_lines else \"\"\n\n return BashOutputResult(\n success=True,\n stdout=stdout,\n stderr=\"\",\n exit_code=bg_shell.exit_code if bg_shell.exit_code is not None else 0,\n bash_id=bash_id,\n )\n\n except ValueError as e:\n # Shell not found\n available_ids = BackgroundShellManager.get_available_ids()\n return BashOutputResult(\n success=False,\n error=f\"{str(e)}. Available: {available_ids or 'none'}\",\n stdout=\"\",\n stderr=str(e),\n exit_code=-1,\n )\n except Exception as e:\n return BashOutputResult(\n success=False,\n error=f\"Failed to terminate bash shell: {str(e)}\",\n stdout=\"\",\n stderr=str(e),\n exit_code=-1,\n )", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 15355}, "tests/test_bash_tool.py::19": {"resolved_imports": ["mini_agent/tools/bash_tool.py"], "used_names": ["BashTool", "asyncio", "pytest"], "enclosing_function": "test_foreground_command", "extracted_code": "# Source: mini_agent/tools/bash_tool.py\nclass BashTool(Tool):\n \"\"\"Execute shell commands in foreground or background.\n\n Automatically detects OS and uses appropriate shell:\n - Windows: PowerShell\n - Unix/Linux/macOS: bash\n \"\"\"\n\n def __init__(self, workspace_dir: str | None = None):\n \"\"\"Initialize BashTool with OS-specific shell detection.\n\n Args:\n workspace_dir: Working directory for command execution.\n If provided, all commands run in this directory.\n If None, commands run in the process's cwd.\n \"\"\"\n self.is_windows = platform.system() == \"Windows\"\n self.shell_name = \"PowerShell\" if self.is_windows else \"bash\"\n self.workspace_dir = workspace_dir\n\n @property\n def name(self) -> str:\n return \"bash\"\n\n @property\n def description(self) -> str:\n shell_examples = {\n \"Windows\": \"\"\"Execute PowerShell commands in foreground or background.\n\nFor terminal operations like git, npm, docker, etc. DO NOT use for file operations - use specialized tools.\n\nParameters:\n - command (required): PowerShell command to execute\n - timeout (optional): Timeout in seconds (default: 120, max: 600) for foreground commands\n - run_in_background (optional): Set true for long-running commands (servers, etc.)\n\nTips:\n - Quote file paths with spaces: cd \"My Documents\"\n - Chain dependent commands with semicolon: git add . ; git commit -m \"msg\"\n - Use absolute paths instead of cd when possible\n - For background commands, monitor with bash_output and terminate with bash_kill\n\nExamples:\n - git status\n - npm test\n - python -m http.server 8080 (with run_in_background=true)\"\"\",\n \"Unix\": \"\"\"Execute bash commands in foreground or background.\n\nFor terminal operations like git, npm, docker, etc. DO NOT use for file operations - use specialized tools.\n\nParameters:\n - command (required): Bash command to execute\n - timeout (optional): Timeout in seconds (default: 120, max: 600) for foreground commands\n - run_in_background (optional): Set true for long-running commands (servers, etc.)\n\nTips:\n - Quote file paths with spaces: cd \"My Documents\"\n - Chain dependent commands with &&: git add . && git commit -m \"msg\"\n - Use absolute paths instead of cd when possible\n - For background commands, monitor with bash_output and terminate with bash_kill\n\nExamples:\n - git status\n - npm test\n - python3 -m http.server 8080 (with run_in_background=true)\"\"\",\n }\n return shell_examples[\"Windows\"] if self.is_windows else shell_examples[\"Unix\"]\n\n @property\n def parameters(self) -> dict[str, Any]:\n cmd_desc = f\"The {self.shell_name} command to execute. Quote file paths with spaces using double quotes.\"\n return {\n \"type\": \"object\",\n \"properties\": {\n \"command\": {\n \"type\": \"string\",\n \"description\": cmd_desc,\n },\n \"timeout\": {\n \"type\": \"integer\",\n \"description\": \"Optional: Timeout in seconds (default: 120, max: 600). Only applies to foreground commands.\",\n \"default\": 120,\n },\n \"run_in_background\": {\n \"type\": \"boolean\",\n \"description\": \"Optional: Set to true to run the command in the background. Use this for long-running commands like servers. You can monitor output using bash_output tool.\",\n \"default\": False,\n },\n },\n \"required\": [\"command\"],\n }\n\n async def execute(\n self,\n command: str,\n timeout: int = 120,\n run_in_background: bool = False,\n ) -> ToolResult:\n \"\"\"Execute shell command with optional background execution.\n\n Args:\n command: The shell command to execute\n timeout: Timeout in seconds (default: 120, max: 600)\n run_in_background: Set true to run command in background\n\n Returns:\n BashExecutionResult with command output and status\n \"\"\"\n\n try:\n # Validate timeout\n if timeout > 600:\n timeout = 600\n elif timeout < 1:\n timeout = 120\n\n # Prepare shell-specific command execution\n if self.is_windows:\n # Windows: Use PowerShell with appropriate encoding\n shell_cmd = [\"powershell.exe\", \"-NoProfile\", \"-Command\", command]\n else:\n # Unix/Linux/macOS: Use bash\n shell_cmd = command\n\n if run_in_background:\n # Background execution: Create isolated process\n bash_id = str(uuid.uuid4())[:8]\n\n # Start background process with combined stdout/stderr\n if self.is_windows:\n process = await asyncio.create_subprocess_exec(\n *shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.STDOUT,\n cwd=self.workspace_dir,\n )\n else:\n process = await asyncio.create_subprocess_shell(\n shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.STDOUT,\n cwd=self.workspace_dir,\n )\n\n # Create background shell and add to manager\n bg_shell = BackgroundShell(bash_id=bash_id, command=command, process=process, start_time=time.time())\n BackgroundShellManager.add(bg_shell)\n\n # Start monitoring task\n await BackgroundShellManager.start_monitor(bash_id)\n\n # Return immediately with bash_id\n message = f\"Command started in background. Use bash_output to monitor (bash_id='{bash_id}').\"\n formatted_content = f\"{message}\\n\\nCommand: {command}\\nBash ID: {bash_id}\"\n\n return BashOutputResult(\n success=True,\n content=formatted_content,\n stdout=f\"Background command started with ID: {bash_id}\",\n stderr=\"\",\n exit_code=0,\n bash_id=bash_id,\n )\n\n else:\n # Foreground execution: Create isolated process\n if self.is_windows:\n process = await asyncio.create_subprocess_exec(\n *shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n cwd=self.workspace_dir,\n )\n else:\n process = await asyncio.create_subprocess_shell(\n shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n cwd=self.workspace_dir,\n )\n\n try:\n stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)\n except asyncio.TimeoutError:\n process.kill()\n error_msg = f\"Command timed out after {timeout} seconds\"\n return BashOutputResult(\n success=False,\n error=error_msg,\n stdout=\"\",\n stderr=error_msg,\n exit_code=-1,\n )\n\n # Decode output\n stdout_text = stdout.decode(\"utf-8\", errors=\"replace\")\n stderr_text = stderr.decode(\"utf-8\", errors=\"replace\")\n\n # Create result (content auto-formatted by model_validator)\n is_success = process.returncode == 0\n error_msg = None\n if not is_success:\n error_msg = f\"Command failed with exit code {process.returncode}\"\n if stderr_text:\n error_msg += f\"\\n{stderr_text.strip()}\"\n\n return BashOutputResult(\n success=is_success,\n error=error_msg,\n stdout=stdout_text,\n stderr=stderr_text,\n exit_code=process.returncode or 0,\n )\n\n except Exception as e:\n return BashOutputResult(\n success=False,\n error=str(e),\n stdout=\"\",\n stderr=str(e),\n exit_code=-1,\n )", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 8734}, "tests/test_bash_tool.py::34": {"resolved_imports": ["mini_agent/tools/bash_tool.py"], "used_names": ["BashTool", "asyncio", "pytest"], "enclosing_function": "test_foreground_command_with_stderr", "extracted_code": "# Source: mini_agent/tools/bash_tool.py\nclass BashTool(Tool):\n \"\"\"Execute shell commands in foreground or background.\n\n Automatically detects OS and uses appropriate shell:\n - Windows: PowerShell\n - Unix/Linux/macOS: bash\n \"\"\"\n\n def __init__(self, workspace_dir: str | None = None):\n \"\"\"Initialize BashTool with OS-specific shell detection.\n\n Args:\n workspace_dir: Working directory for command execution.\n If provided, all commands run in this directory.\n If None, commands run in the process's cwd.\n \"\"\"\n self.is_windows = platform.system() == \"Windows\"\n self.shell_name = \"PowerShell\" if self.is_windows else \"bash\"\n self.workspace_dir = workspace_dir\n\n @property\n def name(self) -> str:\n return \"bash\"\n\n @property\n def description(self) -> str:\n shell_examples = {\n \"Windows\": \"\"\"Execute PowerShell commands in foreground or background.\n\nFor terminal operations like git, npm, docker, etc. DO NOT use for file operations - use specialized tools.\n\nParameters:\n - command (required): PowerShell command to execute\n - timeout (optional): Timeout in seconds (default: 120, max: 600) for foreground commands\n - run_in_background (optional): Set true for long-running commands (servers, etc.)\n\nTips:\n - Quote file paths with spaces: cd \"My Documents\"\n - Chain dependent commands with semicolon: git add . ; git commit -m \"msg\"\n - Use absolute paths instead of cd when possible\n - For background commands, monitor with bash_output and terminate with bash_kill\n\nExamples:\n - git status\n - npm test\n - python -m http.server 8080 (with run_in_background=true)\"\"\",\n \"Unix\": \"\"\"Execute bash commands in foreground or background.\n\nFor terminal operations like git, npm, docker, etc. DO NOT use for file operations - use specialized tools.\n\nParameters:\n - command (required): Bash command to execute\n - timeout (optional): Timeout in seconds (default: 120, max: 600) for foreground commands\n - run_in_background (optional): Set true for long-running commands (servers, etc.)\n\nTips:\n - Quote file paths with spaces: cd \"My Documents\"\n - Chain dependent commands with &&: git add . && git commit -m \"msg\"\n - Use absolute paths instead of cd when possible\n - For background commands, monitor with bash_output and terminate with bash_kill\n\nExamples:\n - git status\n - npm test\n - python3 -m http.server 8080 (with run_in_background=true)\"\"\",\n }\n return shell_examples[\"Windows\"] if self.is_windows else shell_examples[\"Unix\"]\n\n @property\n def parameters(self) -> dict[str, Any]:\n cmd_desc = f\"The {self.shell_name} command to execute. Quote file paths with spaces using double quotes.\"\n return {\n \"type\": \"object\",\n \"properties\": {\n \"command\": {\n \"type\": \"string\",\n \"description\": cmd_desc,\n },\n \"timeout\": {\n \"type\": \"integer\",\n \"description\": \"Optional: Timeout in seconds (default: 120, max: 600). Only applies to foreground commands.\",\n \"default\": 120,\n },\n \"run_in_background\": {\n \"type\": \"boolean\",\n \"description\": \"Optional: Set to true to run the command in the background. Use this for long-running commands like servers. You can monitor output using bash_output tool.\",\n \"default\": False,\n },\n },\n \"required\": [\"command\"],\n }\n\n async def execute(\n self,\n command: str,\n timeout: int = 120,\n run_in_background: bool = False,\n ) -> ToolResult:\n \"\"\"Execute shell command with optional background execution.\n\n Args:\n command: The shell command to execute\n timeout: Timeout in seconds (default: 120, max: 600)\n run_in_background: Set true to run command in background\n\n Returns:\n BashExecutionResult with command output and status\n \"\"\"\n\n try:\n # Validate timeout\n if timeout > 600:\n timeout = 600\n elif timeout < 1:\n timeout = 120\n\n # Prepare shell-specific command execution\n if self.is_windows:\n # Windows: Use PowerShell with appropriate encoding\n shell_cmd = [\"powershell.exe\", \"-NoProfile\", \"-Command\", command]\n else:\n # Unix/Linux/macOS: Use bash\n shell_cmd = command\n\n if run_in_background:\n # Background execution: Create isolated process\n bash_id = str(uuid.uuid4())[:8]\n\n # Start background process with combined stdout/stderr\n if self.is_windows:\n process = await asyncio.create_subprocess_exec(\n *shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.STDOUT,\n cwd=self.workspace_dir,\n )\n else:\n process = await asyncio.create_subprocess_shell(\n shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.STDOUT,\n cwd=self.workspace_dir,\n )\n\n # Create background shell and add to manager\n bg_shell = BackgroundShell(bash_id=bash_id, command=command, process=process, start_time=time.time())\n BackgroundShellManager.add(bg_shell)\n\n # Start monitoring task\n await BackgroundShellManager.start_monitor(bash_id)\n\n # Return immediately with bash_id\n message = f\"Command started in background. Use bash_output to monitor (bash_id='{bash_id}').\"\n formatted_content = f\"{message}\\n\\nCommand: {command}\\nBash ID: {bash_id}\"\n\n return BashOutputResult(\n success=True,\n content=formatted_content,\n stdout=f\"Background command started with ID: {bash_id}\",\n stderr=\"\",\n exit_code=0,\n bash_id=bash_id,\n )\n\n else:\n # Foreground execution: Create isolated process\n if self.is_windows:\n process = await asyncio.create_subprocess_exec(\n *shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n cwd=self.workspace_dir,\n )\n else:\n process = await asyncio.create_subprocess_shell(\n shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n cwd=self.workspace_dir,\n )\n\n try:\n stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)\n except asyncio.TimeoutError:\n process.kill()\n error_msg = f\"Command timed out after {timeout} seconds\"\n return BashOutputResult(\n success=False,\n error=error_msg,\n stdout=\"\",\n stderr=error_msg,\n exit_code=-1,\n )\n\n # Decode output\n stdout_text = stdout.decode(\"utf-8\", errors=\"replace\")\n stderr_text = stderr.decode(\"utf-8\", errors=\"replace\")\n\n # Create result (content auto-formatted by model_validator)\n is_success = process.returncode == 0\n error_msg = None\n if not is_success:\n error_msg = f\"Command failed with exit code {process.returncode}\"\n if stderr_text:\n error_msg += f\"\\n{stderr_text.strip()}\"\n\n return BashOutputResult(\n success=is_success,\n error=error_msg,\n stdout=stdout_text,\n stderr=stderr_text,\n exit_code=process.returncode or 0,\n )\n\n except Exception as e:\n return BashOutputResult(\n success=False,\n error=str(e),\n stdout=\"\",\n stderr=str(e),\n exit_code=-1,\n )", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 8734}, "tests/test_bash_tool.py::62": {"resolved_imports": ["mini_agent/tools/bash_tool.py"], "used_names": ["BashTool", "asyncio", "pytest"], "enclosing_function": "test_command_timeout", "extracted_code": "# Source: mini_agent/tools/bash_tool.py\nclass BashTool(Tool):\n \"\"\"Execute shell commands in foreground or background.\n\n Automatically detects OS and uses appropriate shell:\n - Windows: PowerShell\n - Unix/Linux/macOS: bash\n \"\"\"\n\n def __init__(self, workspace_dir: str | None = None):\n \"\"\"Initialize BashTool with OS-specific shell detection.\n\n Args:\n workspace_dir: Working directory for command execution.\n If provided, all commands run in this directory.\n If None, commands run in the process's cwd.\n \"\"\"\n self.is_windows = platform.system() == \"Windows\"\n self.shell_name = \"PowerShell\" if self.is_windows else \"bash\"\n self.workspace_dir = workspace_dir\n\n @property\n def name(self) -> str:\n return \"bash\"\n\n @property\n def description(self) -> str:\n shell_examples = {\n \"Windows\": \"\"\"Execute PowerShell commands in foreground or background.\n\nFor terminal operations like git, npm, docker, etc. DO NOT use for file operations - use specialized tools.\n\nParameters:\n - command (required): PowerShell command to execute\n - timeout (optional): Timeout in seconds (default: 120, max: 600) for foreground commands\n - run_in_background (optional): Set true for long-running commands (servers, etc.)\n\nTips:\n - Quote file paths with spaces: cd \"My Documents\"\n - Chain dependent commands with semicolon: git add . ; git commit -m \"msg\"\n - Use absolute paths instead of cd when possible\n - For background commands, monitor with bash_output and terminate with bash_kill\n\nExamples:\n - git status\n - npm test\n - python -m http.server 8080 (with run_in_background=true)\"\"\",\n \"Unix\": \"\"\"Execute bash commands in foreground or background.\n\nFor terminal operations like git, npm, docker, etc. DO NOT use for file operations - use specialized tools.\n\nParameters:\n - command (required): Bash command to execute\n - timeout (optional): Timeout in seconds (default: 120, max: 600) for foreground commands\n - run_in_background (optional): Set true for long-running commands (servers, etc.)\n\nTips:\n - Quote file paths with spaces: cd \"My Documents\"\n - Chain dependent commands with &&: git add . && git commit -m \"msg\"\n - Use absolute paths instead of cd when possible\n - For background commands, monitor with bash_output and terminate with bash_kill\n\nExamples:\n - git status\n - npm test\n - python3 -m http.server 8080 (with run_in_background=true)\"\"\",\n }\n return shell_examples[\"Windows\"] if self.is_windows else shell_examples[\"Unix\"]\n\n @property\n def parameters(self) -> dict[str, Any]:\n cmd_desc = f\"The {self.shell_name} command to execute. Quote file paths with spaces using double quotes.\"\n return {\n \"type\": \"object\",\n \"properties\": {\n \"command\": {\n \"type\": \"string\",\n \"description\": cmd_desc,\n },\n \"timeout\": {\n \"type\": \"integer\",\n \"description\": \"Optional: Timeout in seconds (default: 120, max: 600). Only applies to foreground commands.\",\n \"default\": 120,\n },\n \"run_in_background\": {\n \"type\": \"boolean\",\n \"description\": \"Optional: Set to true to run the command in the background. Use this for long-running commands like servers. You can monitor output using bash_output tool.\",\n \"default\": False,\n },\n },\n \"required\": [\"command\"],\n }\n\n async def execute(\n self,\n command: str,\n timeout: int = 120,\n run_in_background: bool = False,\n ) -> ToolResult:\n \"\"\"Execute shell command with optional background execution.\n\n Args:\n command: The shell command to execute\n timeout: Timeout in seconds (default: 120, max: 600)\n run_in_background: Set true to run command in background\n\n Returns:\n BashExecutionResult with command output and status\n \"\"\"\n\n try:\n # Validate timeout\n if timeout > 600:\n timeout = 600\n elif timeout < 1:\n timeout = 120\n\n # Prepare shell-specific command execution\n if self.is_windows:\n # Windows: Use PowerShell with appropriate encoding\n shell_cmd = [\"powershell.exe\", \"-NoProfile\", \"-Command\", command]\n else:\n # Unix/Linux/macOS: Use bash\n shell_cmd = command\n\n if run_in_background:\n # Background execution: Create isolated process\n bash_id = str(uuid.uuid4())[:8]\n\n # Start background process with combined stdout/stderr\n if self.is_windows:\n process = await asyncio.create_subprocess_exec(\n *shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.STDOUT,\n cwd=self.workspace_dir,\n )\n else:\n process = await asyncio.create_subprocess_shell(\n shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.STDOUT,\n cwd=self.workspace_dir,\n )\n\n # Create background shell and add to manager\n bg_shell = BackgroundShell(bash_id=bash_id, command=command, process=process, start_time=time.time())\n BackgroundShellManager.add(bg_shell)\n\n # Start monitoring task\n await BackgroundShellManager.start_monitor(bash_id)\n\n # Return immediately with bash_id\n message = f\"Command started in background. Use bash_output to monitor (bash_id='{bash_id}').\"\n formatted_content = f\"{message}\\n\\nCommand: {command}\\nBash ID: {bash_id}\"\n\n return BashOutputResult(\n success=True,\n content=formatted_content,\n stdout=f\"Background command started with ID: {bash_id}\",\n stderr=\"\",\n exit_code=0,\n bash_id=bash_id,\n )\n\n else:\n # Foreground execution: Create isolated process\n if self.is_windows:\n process = await asyncio.create_subprocess_exec(\n *shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n cwd=self.workspace_dir,\n )\n else:\n process = await asyncio.create_subprocess_shell(\n shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n cwd=self.workspace_dir,\n )\n\n try:\n stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)\n except asyncio.TimeoutError:\n process.kill()\n error_msg = f\"Command timed out after {timeout} seconds\"\n return BashOutputResult(\n success=False,\n error=error_msg,\n stdout=\"\",\n stderr=error_msg,\n exit_code=-1,\n )\n\n # Decode output\n stdout_text = stdout.decode(\"utf-8\", errors=\"replace\")\n stderr_text = stderr.decode(\"utf-8\", errors=\"replace\")\n\n # Create result (content auto-formatted by model_validator)\n is_success = process.returncode == 0\n error_msg = None\n if not is_success:\n error_msg = f\"Command failed with exit code {process.returncode}\"\n if stderr_text:\n error_msg += f\"\\n{stderr_text.strip()}\"\n\n return BashOutputResult(\n success=is_success,\n error=error_msg,\n stdout=stdout_text,\n stderr=stderr_text,\n exit_code=process.returncode or 0,\n )\n\n except Exception as e:\n return BashOutputResult(\n success=False,\n error=str(e),\n stdout=\"\",\n stderr=str(e),\n exit_code=-1,\n )", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 8734}, "tests/test_integration.py::206": {"resolved_imports": ["mini_agent/llm/__init__.py", "mini_agent/agent.py", "mini_agent/config.py", "mini_agent/tools/bash_tool.py", "mini_agent/tools/file_tools.py", "mini_agent/tools/mcp_loader.py", "mini_agent/tools/note_tool.py"], "used_names": ["Agent", "Config", "LLMClient", "Path", "RecallNoteTool", "SessionNoteTool", "asyncio", "json", "pytest", "tempfile"], "enclosing_function": "test_session_memory_demo", "extracted_code": "# Source: mini_agent/llm/__init__.py\n\nfrom .anthropic_client import AnthropicClient\nfrom .base import LLMClientBase\nfrom .llm_wrapper import LLMClient\nfrom .openai_client import OpenAIClient\n\n__all__ = [\"LLMClientBase\", \"AnthropicClient\", \"OpenAIClient\", \"LLMClient\"]\n\n\nfrom .anthropic_client import AnthropicClient\nfrom .base import LLMClientBase\nfrom .llm_wrapper import LLMClient\nfrom .openai_client import OpenAIClient\n\n__all__ = [\"LLMClientBase\", \"AnthropicClient\", \"OpenAIClient\", \"LLMClient\"]\n\n\nfrom .openai_client import OpenAIClient\n\n__all__ = [\"LLMClientBase\", \"AnthropicClient\", \"OpenAIClient\", \"LLMClient\"]\n\n\n\n# Source: mini_agent/agent.py\nclass Agent:\n \"\"\"Single agent with basic tools and MCP support.\"\"\"\n\n def __init__(\n self,\n llm_client: LLMClient,\n system_prompt: str,\n tools: list[Tool],\n max_steps: int = 50,\n workspace_dir: str = \"./workspace\",\n token_limit: int = 80000, # Summary triggered when tokens exceed this value\n ):\n self.llm = llm_client\n self.tools = {tool.name: tool for tool in tools}\n self.max_steps = max_steps\n self.token_limit = token_limit\n self.workspace_dir = Path(workspace_dir)\n # Cancellation event for interrupting agent execution (set externally, e.g., by Esc key)\n self.cancel_event: Optional[asyncio.Event] = None\n\n # Ensure workspace exists\n self.workspace_dir.mkdir(parents=True, exist_ok=True)\n\n # Inject workspace information into system prompt if not already present\n if \"Current Workspace\" not in system_prompt:\n workspace_info = f\"\\n\\n## Current Workspace\\nYou are currently working in: `{self.workspace_dir.absolute()}`\\nAll relative paths will be resolved relative to this directory.\"\n system_prompt = system_prompt + workspace_info\n\n self.system_prompt = system_prompt\n\n # Initialize message history\n self.messages: list[Message] = [Message(role=\"system\", content=system_prompt)]\n\n # Initialize logger\n self.logger = AgentLogger()\n\n # Token usage from last API response (updated after each LLM call)\n self.api_total_tokens: int = 0\n # Flag to skip token check right after summary (avoid consecutive triggers)\n self._skip_next_token_check: bool = False\n\n def add_user_message(self, content: str):\n \"\"\"Add a user message to history.\"\"\"\n self.messages.append(Message(role=\"user\", content=content))\n\n def _check_cancelled(self) -> bool:\n \"\"\"Check if agent execution has been cancelled.\n\n Returns:\n True if cancelled, False otherwise.\n \"\"\"\n if self.cancel_event is not None and self.cancel_event.is_set():\n return True\n return False\n\n def _cleanup_incomplete_messages(self):\n \"\"\"Remove the incomplete assistant message and its partial tool results.\n\n This ensures message consistency after cancellation by removing\n only the current step's incomplete messages, preserving completed steps.\n \"\"\"\n # Find the index of the last assistant message\n last_assistant_idx = -1\n for i in range(len(self.messages) - 1, -1, -1):\n if self.messages[i].role == \"assistant\":\n last_assistant_idx = i\n break\n\n if last_assistant_idx == -1:\n # No assistant message found, nothing to clean\n return\n\n # Remove the last assistant message and all tool results after it\n removed_count = len(self.messages) - last_assistant_idx\n if removed_count > 0:\n self.messages = self.messages[:last_assistant_idx]\n print(f\"{Colors.DIM} Cleaned up {removed_count} incomplete message(s){Colors.RESET}\")\n\n def _estimate_tokens(self) -> int:\n \"\"\"Accurately calculate token count for message history using tiktoken\n\n Uses cl100k_base encoder (GPT-4/Claude/M2 compatible)\n \"\"\"\n try:\n # Use cl100k_base encoder (used by GPT-4 and most modern models)\n encoding = tiktoken.get_encoding(\"cl100k_base\")\n except Exception:\n # Fallback: if tiktoken initialization fails, use simple estimation\n return self._estimate_tokens_fallback()\n\n total_tokens = 0\n\n for msg in self.messages:\n # Count text content\n if isinstance(msg.content, str):\n total_tokens += len(encoding.encode(msg.content))\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n # Convert dict to string for calculation\n total_tokens += len(encoding.encode(str(block)))\n\n # Count thinking\n if msg.thinking:\n total_tokens += len(encoding.encode(msg.thinking))\n\n # Count tool_calls\n if msg.tool_calls:\n total_tokens += len(encoding.encode(str(msg.tool_calls)))\n\n # Metadata overhead per message (approximately 4 tokens)\n total_tokens += 4\n\n return total_tokens\n\n def _estimate_tokens_fallback(self) -> int:\n \"\"\"Fallback token estimation method (when tiktoken is unavailable)\"\"\"\n total_chars = 0\n for msg in self.messages:\n if isinstance(msg.content, str):\n total_chars += len(msg.content)\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n total_chars += len(str(block))\n\n if msg.thinking:\n total_chars += len(msg.thinking)\n\n if msg.tool_calls:\n total_chars += len(str(msg.tool_calls))\n\n # Rough estimation: average 2.5 characters = 1 token\n return int(total_chars / 2.5)\n\n async def _summarize_messages(self):\n \"\"\"Message history summarization: summarize conversations between user messages when tokens exceed limit\n\n Strategy (Agent mode):\n - Keep all user messages (these are user intents)\n - Summarize content between each user-user pair (agent execution process)\n - If last round is still executing (has agent/tool messages but no next user), also summarize\n - Structure: system -> user1 -> summary1 -> user2 -> summary2 -> user3 -> summary3 (if executing)\n\n Summary is triggered when EITHER:\n - Local token estimation exceeds limit\n - API reported total_tokens exceeds limit\n \"\"\"\n # Skip check if we just completed a summary (wait for next LLM call to update api_total_tokens)\n if self._skip_next_token_check:\n self._skip_next_token_check = False\n return\n\n estimated_tokens = self._estimate_tokens()\n\n # Check both local estimation and API reported tokens\n should_summarize = estimated_tokens > self.token_limit or self.api_total_tokens > self.token_limit\n\n # If neither exceeded, no summary needed\n if not should_summarize:\n return\n\n print(\n f\"\\n{Colors.BRIGHT_YELLOW}📊 Token usage - Local estimate: {estimated_tokens}, API reported: {self.api_total_tokens}, Limit: {self.token_limit}{Colors.RESET}\"\n )\n print(f\"{Colors.BRIGHT_YELLOW}🔄 Triggering message history summarization...{Colors.RESET}\")\n\n # Find all user message indices (skip system prompt)\n user_indices = [i for i, msg in enumerate(self.messages) if msg.role == \"user\" and i > 0]\n\n # Need at least 1 user message to perform summary\n if len(user_indices) < 1:\n print(f\"{Colors.BRIGHT_YELLOW}⚠️ Insufficient messages, cannot summarize{Colors.RESET}\")\n return\n\n # Build new message list\n new_messages = [self.messages[0]] # Keep system prompt\n summary_count = 0\n\n # Iterate through each user message and summarize the execution process after it\n for i, user_idx in enumerate(user_indices):\n # Add current user message\n new_messages.append(self.messages[user_idx])\n\n # Determine message range to summarize\n # If last user, go to end of message list; otherwise to before next user\n if i < len(user_indices) - 1:\n next_user_idx = user_indices[i + 1]\n else:\n next_user_idx = len(self.messages)\n\n # Extract execution messages for this round\n execution_messages = self.messages[user_idx + 1 : next_user_idx]\n\n # If there are execution messages in this round, summarize them\n if execution_messages:\n summary_text = await self._create_summary(execution_messages, i + 1)\n if summary_text:\n summary_message = Message(\n role=\"user\",\n content=f\"[Assistant Execution Summary]\\n\\n{summary_text}\",\n )\n new_messages.append(summary_message)\n summary_count += 1\n\n # Replace message list\n self.messages = new_messages\n\n # Skip next token check to avoid consecutive summary triggers\n # (api_total_tokens will be updated after next LLM call)\n self._skip_next_token_check = True\n\n new_tokens = self._estimate_tokens()\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary completed, local tokens: {estimated_tokens} → {new_tokens}{Colors.RESET}\")\n print(f\"{Colors.DIM} Structure: system + {len(user_indices)} user messages + {summary_count} summaries{Colors.RESET}\")\n print(f\"{Colors.DIM} Note: API token count will update on next LLM call{Colors.RESET}\")\n\n async def _create_summary(self, messages: list[Message], round_num: int) -> str:\n \"\"\"Create summary for one execution round\n\n Args:\n messages: List of messages to summarize\n round_num: Round number\n\n Returns:\n Summary text\n \"\"\"\n if not messages:\n return \"\"\n\n # Build summary content\n summary_content = f\"Round {round_num} execution process:\\n\\n\"\n for msg in messages:\n if msg.role == \"assistant\":\n content_text = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\"Assistant: {content_text}\\n\"\n if msg.tool_calls:\n tool_names = [tc.function.name for tc in msg.tool_calls]\n summary_content += f\" → Called tools: {', '.join(tool_names)}\\n\"\n elif msg.role == \"tool\":\n result_preview = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\" ← Tool returned: {result_preview}...\\n\"\n\n # Call LLM to generate concise summary\n try:\n summary_prompt = f\"\"\"Please provide a concise summary of the following Agent execution process:\n\n{summary_content}\n\nRequirements:\n1. Focus on what tasks were completed and which tools were called\n2. Keep key execution results and important findings\n3. Be concise and clear, within 1000 words\n4. Use English\n5. Do not include \"user\" related content, only summarize the Agent's execution process\"\"\"\n\n summary_msg = Message(role=\"user\", content=summary_prompt)\n response = await self.llm.generate(\n messages=[\n Message(\n role=\"system\",\n content=\"You are an assistant skilled at summarizing Agent execution processes.\",\n ),\n summary_msg,\n ]\n )\n\n summary_text = response.content\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary for round {round_num} generated successfully{Colors.RESET}\")\n return summary_text\n\n except Exception as e:\n print(f\"{Colors.BRIGHT_RED}✗ Summary generation failed for round {round_num}: {e}{Colors.RESET}\")\n # Use simple text summary on failure\n return summary_content\n\n async def run(self, cancel_event: Optional[asyncio.Event] = None) -> str:\n \"\"\"Execute agent loop until task is complete or max steps reached.\n\n Args:\n cancel_event: Optional asyncio.Event that can be set to cancel execution.\n When set, the agent will stop at the next safe checkpoint\n (after completing the current step to keep messages consistent).\n\n Returns:\n The final response content, or error message (including cancellation message).\n \"\"\"\n # Set cancellation event (can also be set via self.cancel_event before calling run())\n if cancel_event is not None:\n self.cancel_event = cancel_event\n\n # Start new run, initialize log file\n self.logger.start_new_run()\n print(f\"{Colors.DIM}📝 Log file: {self.logger.get_log_file_path()}{Colors.RESET}\")\n\n step = 0\n run_start_time = perf_counter()\n\n while step < self.max_steps:\n # Check for cancellation at start of each step\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_start_time = perf_counter()\n # Check and summarize message history to prevent context overflow\n await self._summarize_messages()\n\n # Step header with proper width calculation\n BOX_WIDTH = 58\n step_text = f\"{Colors.BOLD}{Colors.BRIGHT_CYAN}💭 Step {step + 1}/{self.max_steps}{Colors.RESET}\"\n step_display_width = calculate_display_width(step_text)\n padding = max(0, BOX_WIDTH - 1 - step_display_width) # -1 for leading space\n\n print(f\"\\n{Colors.DIM}╭{'─' * BOX_WIDTH}╮{Colors.RESET}\")\n print(f\"{Colors.DIM}│{Colors.RESET} {step_text}{' ' * padding}{Colors.DIM}│{Colors.RESET}\")\n print(f\"{Colors.DIM}╰{'─' * BOX_WIDTH}╯{Colors.RESET}\")\n\n # Get tool list for LLM call\n tool_list = list(self.tools.values())\n\n # Log LLM request and call LLM with Tool objects directly\n self.logger.log_request(messages=self.messages, tools=tool_list)\n\n try:\n response = await self.llm.generate(messages=self.messages, tools=tool_list)\n except Exception as e:\n # Check if it's a retry exhausted error\n from .retry import RetryExhaustedError\n\n if isinstance(e, RetryExhaustedError):\n error_msg = f\"LLM call failed after {e.attempts} retries\\nLast error: {str(e.last_exception)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Retry failed:{Colors.RESET} {error_msg}\")\n else:\n error_msg = f\"LLM call failed: {str(e)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Error:{Colors.RESET} {error_msg}\")\n return error_msg\n\n # Accumulate API reported token usage\n if response.usage:\n self.api_total_tokens = response.usage.total_tokens\n\n # Log LLM response\n self.logger.log_response(\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n finish_reason=response.finish_reason,\n )\n\n # Add assistant message\n assistant_msg = Message(\n role=\"assistant\",\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n )\n self.messages.append(assistant_msg)\n\n # Print thinking if present\n if response.thinking:\n print(f\"\\n{Colors.BOLD}{Colors.MAGENTA}🧠 Thinking:{Colors.RESET}\")\n print(f\"{Colors.DIM}{response.thinking}{Colors.RESET}\")\n\n # Print assistant response\n if response.content:\n print(f\"\\n{Colors.BOLD}{Colors.BRIGHT_BLUE}🤖 Assistant:{Colors.RESET}\")\n print(f\"{response.content}\")\n\n # Check if task is complete (no tool calls)\n if not response.tool_calls:\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n return response.content\n\n # Check for cancellation before executing tools\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n # Execute tool calls\n for tool_call in response.tool_calls:\n tool_call_id = tool_call.id\n function_name = tool_call.function.name\n arguments = tool_call.function.arguments\n\n # Tool call header\n print(f\"\\n{Colors.BRIGHT_YELLOW}🔧 Tool Call:{Colors.RESET} {Colors.BOLD}{Colors.CYAN}{function_name}{Colors.RESET}\")\n\n # Arguments (formatted display)\n print(f\"{Colors.DIM} Arguments:{Colors.RESET}\")\n # Truncate each argument value to avoid overly long output\n truncated_args = {}\n for key, value in arguments.items():\n value_str = str(value)\n if len(value_str) > 200:\n truncated_args[key] = value_str[:200] + \"...\"\n else:\n truncated_args[key] = value\n args_json = json.dumps(truncated_args, indent=2, ensure_ascii=False)\n for line in args_json.split(\"\\n\"):\n print(f\" {Colors.DIM}{line}{Colors.RESET}\")\n\n # Execute tool\n if function_name not in self.tools:\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Unknown tool: {function_name}\",\n )\n else:\n try:\n tool = self.tools[function_name]\n result = await tool.execute(**arguments)\n except Exception as e:\n # Catch all exceptions during tool execution, convert to failed ToolResult\n import traceback\n\n error_detail = f\"{type(e).__name__}: {str(e)}\"\n error_trace = traceback.format_exc()\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Tool execution failed: {error_detail}\\n\\nTraceback:\\n{error_trace}\",\n )\n\n # Log tool execution result\n self.logger.log_tool_result(\n tool_name=function_name,\n arguments=arguments,\n result_success=result.success,\n result_content=result.content if result.success else None,\n result_error=result.error if not result.success else None,\n )\n\n # Print result\n if result.success:\n result_text = result.content\n if len(result_text) > 300:\n result_text = result_text[:300] + f\"{Colors.DIM}...{Colors.RESET}\"\n print(f\"{Colors.BRIGHT_GREEN}✓ Result:{Colors.RESET} {result_text}\")\n else:\n print(f\"{Colors.BRIGHT_RED}✗ Error:{Colors.RESET} {Colors.RED}{result.error}{Colors.RESET}\")\n\n # Add tool result message\n tool_msg = Message(\n role=\"tool\",\n content=result.content if result.success else f\"Error: {result.error}\",\n tool_call_id=tool_call_id,\n name=function_name,\n )\n self.messages.append(tool_msg)\n\n # Check for cancellation after each tool execution\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n\n step += 1\n\n # Max steps reached\n error_msg = f\"Task couldn't be completed after {self.max_steps} steps.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {error_msg}{Colors.RESET}\")\n return error_msg\n\n def get_history(self) -> list[Message]:\n \"\"\"Get message history.\"\"\"\n return self.messages.copy()\n\n\n# Source: mini_agent/config.py\nclass Config(BaseModel):\n \"\"\"Main configuration class\"\"\"\n\n llm: LLMConfig\n agent: AgentConfig\n tools: ToolsConfig\n\n @classmethod\n def load(cls) -> \"Config\":\n \"\"\"Load configuration from the default search path.\"\"\"\n config_path = cls.get_default_config_path()\n if not config_path.exists():\n raise FileNotFoundError(\"Configuration file not found. Run scripts/setup-config.sh or place config.yaml in mini_agent/config/.\")\n return cls.from_yaml(config_path)\n\n @classmethod\n def from_yaml(cls, config_path: str | Path) -> \"Config\":\n \"\"\"Load configuration from YAML file\n\n Args:\n config_path: Configuration file path\n\n Returns:\n Config instance\n\n Raises:\n FileNotFoundError: Configuration file does not exist\n ValueError: Invalid configuration format or missing required fields\n \"\"\"\n config_path = Path(config_path)\n\n if not config_path.exists():\n raise FileNotFoundError(f\"Configuration file does not exist: {config_path}\")\n\n with open(config_path, encoding=\"utf-8\") as f:\n data = yaml.safe_load(f)\n\n if not data:\n raise ValueError(\"Configuration file is empty\")\n\n # Parse LLM configuration\n if \"api_key\" not in data:\n raise ValueError(\"Configuration file missing required field: api_key\")\n\n if not data[\"api_key\"] or data[\"api_key\"] == \"YOUR_API_KEY_HERE\":\n raise ValueError(\"Please configure a valid API Key\")\n\n # Parse retry configuration\n retry_data = data.get(\"retry\", {})\n retry_config = RetryConfig(\n enabled=retry_data.get(\"enabled\", True),\n max_retries=retry_data.get(\"max_retries\", 3),\n initial_delay=retry_data.get(\"initial_delay\", 1.0),\n max_delay=retry_data.get(\"max_delay\", 60.0),\n exponential_base=retry_data.get(\"exponential_base\", 2.0),\n )\n\n llm_config = LLMConfig(\n api_key=data[\"api_key\"],\n api_base=data.get(\"api_base\", \"https://api.minimax.io\"),\n model=data.get(\"model\", \"MiniMax-M2.5\"),\n provider=data.get(\"provider\", \"anthropic\"),\n retry=retry_config,\n )\n\n # Parse Agent configuration\n agent_config = AgentConfig(\n max_steps=data.get(\"max_steps\", 50),\n workspace_dir=data.get(\"workspace_dir\", \"./workspace\"),\n system_prompt_path=data.get(\"system_prompt_path\", \"system_prompt.md\"),\n )\n\n # Parse tools configuration\n tools_data = data.get(\"tools\", {})\n\n # Parse MCP configuration\n mcp_data = tools_data.get(\"mcp\", {})\n mcp_config = MCPConfig(\n connect_timeout=mcp_data.get(\"connect_timeout\", 10.0),\n execute_timeout=mcp_data.get(\"execute_timeout\", 60.0),\n sse_read_timeout=mcp_data.get(\"sse_read_timeout\", 120.0),\n )\n\n tools_config = ToolsConfig(\n enable_file_tools=tools_data.get(\"enable_file_tools\", True),\n enable_bash=tools_data.get(\"enable_bash\", True),\n enable_note=tools_data.get(\"enable_note\", True),\n enable_skills=tools_data.get(\"enable_skills\", True),\n skills_dir=tools_data.get(\"skills_dir\", \"./skills\"),\n enable_mcp=tools_data.get(\"enable_mcp\", True),\n mcp_config_path=tools_data.get(\"mcp_config_path\", \"mcp.json\"),\n mcp=mcp_config,\n )\n\n return cls(\n llm=llm_config,\n agent=agent_config,\n tools=tools_config,\n )\n\n @staticmethod\n def get_package_dir() -> Path:\n \"\"\"Get the package installation directory\n\n Returns:\n Path to the mini_agent package directory\n \"\"\"\n # Get the directory where this config.py file is located\n return Path(__file__).parent\n\n @classmethod\n def find_config_file(cls, filename: str) -> Path | None:\n \"\"\"Find configuration file with priority order\n\n Search for config file in the following order of priority:\n 1) mini_agent/config/{filename} in current directory (development mode)\n 2) ~/.mini-agent/config/{filename} in user home directory\n 3) {package}/mini_agent/config/{filename} in package installation directory\n\n Args:\n filename: Configuration file name (e.g., \"config.yaml\", \"mcp.json\", \"system_prompt.md\")\n\n Returns:\n Path to found config file, or None if not found\n \"\"\"\n # Priority 1: Development mode - current directory's config/ subdirectory\n dev_config = Path.cwd() / \"mini_agent\" / \"config\" / filename\n if dev_config.exists():\n return dev_config\n\n # Priority 2: User config directory\n user_config = Path.home() / \".mini-agent\" / \"config\" / filename\n if user_config.exists():\n return user_config\n\n # Priority 3: Package installation directory's config/ subdirectory\n package_config = cls.get_package_dir() / \"config\" / filename\n if package_config.exists():\n return package_config\n\n return None\n\n @classmethod\n def get_default_config_path(cls) -> Path:\n \"\"\"Get the default config file path with priority search\n\n Returns:\n Path to config.yaml (prioritizes: dev config/ > user config/ > package config/)\n \"\"\"\n config_path = cls.find_config_file(\"config.yaml\")\n if config_path:\n return config_path\n\n # Fallback to package config directory for error message purposes\n return cls.get_package_dir() / \"config\" / \"config.yaml\"\n\n\n# Source: mini_agent/tools/note_tool.py\nclass SessionNoteTool(Tool):\n \"\"\"Tool for recording and recalling session notes.\n\n The agent can use this tool to:\n - Record important facts, decisions, or context during sessions\n - Recall information from previous sessions\n - Build up knowledge over time\n\n Example usage by agent:\n - record_note(\"User prefers concise responses\")\n - record_note(\"Project uses Python 3.12 and async/await\")\n - recall_notes() -> retrieves all recorded notes\n \"\"\"\n\n def __init__(self, memory_file: str = \"./workspace/.agent_memory.json\"):\n \"\"\"Initialize session note tool.\n\n Args:\n memory_file: Path to the note storage file\n \"\"\"\n self.memory_file = Path(memory_file)\n # Lazy loading: file and directory are only created when first note is recorded\n\n @property\n def name(self) -> str:\n return \"record_note\"\n\n @property\n def description(self) -> str:\n return (\n \"Record important information as session notes for future reference. \"\n \"Use this to record key facts, user preferences, decisions, or context \"\n \"that should be recalled later in the agent execution chain. Each note is timestamped.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"content\": {\n \"type\": \"string\",\n \"description\": \"The information to record as a note. Be concise but specific.\",\n },\n \"category\": {\n \"type\": \"string\",\n \"description\": \"Optional category/tag for this note (e.g., 'user_preference', 'project_info', 'decision')\",\n },\n },\n \"required\": [\"content\"],\n }\n\n def _load_from_file(self) -> list:\n \"\"\"Load notes from file.\n \n Returns empty list if file doesn't exist (lazy loading).\n \"\"\"\n if not self.memory_file.exists():\n return []\n \n try:\n return json.loads(self.memory_file.read_text())\n except Exception:\n return []\n\n def _save_to_file(self, notes: list):\n \"\"\"Save notes to file.\n \n Creates parent directory and file if they don't exist (lazy initialization).\n \"\"\"\n # Ensure parent directory exists when actually saving\n self.memory_file.parent.mkdir(parents=True, exist_ok=True)\n self.memory_file.write_text(json.dumps(notes, indent=2, ensure_ascii=False))\n\n async def execute(self, content: str, category: str = \"general\") -> ToolResult:\n \"\"\"Record a session note.\n\n Args:\n content: The information to record\n category: Category/tag for this note\n\n Returns:\n ToolResult with success status\n \"\"\"\n try:\n # Load existing notes\n notes = self._load_from_file()\n\n # Add new note with timestamp\n note = {\n \"timestamp\": datetime.now().isoformat(),\n \"category\": category,\n \"content\": content,\n }\n notes.append(note)\n\n # Save back to file\n self._save_to_file(notes)\n\n return ToolResult(\n success=True,\n content=f\"Recorded note: {content} (category: {category})\",\n )\n except Exception as e:\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"Failed to record note: {str(e)}\",\n )\n\nclass RecallNoteTool(Tool):\n \"\"\"Tool for recalling recorded session notes.\"\"\"\n\n def __init__(self, memory_file: str = \"./workspace/.agent_memory.json\"):\n \"\"\"Initialize recall note tool.\n\n Args:\n memory_file: Path to the note storage file\n \"\"\"\n self.memory_file = Path(memory_file)\n\n @property\n def name(self) -> str:\n return \"recall_notes\"\n\n @property\n def description(self) -> str:\n return (\n \"Recall all previously recorded session notes. \"\n \"Use this to retrieve important information, context, or decisions \"\n \"from earlier in the session or previous agent execution chains.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"category\": {\n \"type\": \"string\",\n \"description\": \"Optional: filter notes by category\",\n },\n },\n }\n\n async def execute(self, category: str = None) -> ToolResult:\n \"\"\"Recall session notes.\n\n Args:\n category: Optional category filter\n\n Returns:\n ToolResult with notes content\n \"\"\"\n try:\n if not self.memory_file.exists():\n return ToolResult(\n success=True,\n content=\"No notes recorded yet.\",\n )\n\n notes = json.loads(self.memory_file.read_text())\n\n if not notes:\n return ToolResult(\n success=True,\n content=\"No notes recorded yet.\",\n )\n\n # Filter by category if specified\n if category:\n notes = [n for n in notes if n.get(\"category\") == category]\n if not notes:\n return ToolResult(\n success=True,\n content=f\"No notes found in category: {category}\",\n )\n\n # Format notes for display\n formatted = []\n for idx, note in enumerate(notes, 1):\n timestamp = note.get(\"timestamp\", \"unknown time\")\n cat = note.get(\"category\", \"general\")\n content = note.get(\"content\", \"\")\n formatted.append(f\"{idx}. [{cat}] {content}\\n (recorded at {timestamp})\")\n\n result = \"Recorded Notes:\\n\" + \"\\n\".join(formatted)\n\n return ToolResult(success=True, content=result)\n\n except Exception as e:\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"Failed to recall notes: {str(e)}\",\n )", "n_imports_parsed": 11, "n_files_resolved": 7, "n_chars_extracted": 33490}, "tests/test_llm.py::77": {"resolved_imports": ["mini_agent/llm/llm_wrapper.py", "mini_agent/schema/schema.py"], "used_names": ["LLMClient", "LLMProvider", "Message", "Path", "asyncio", "pytest", "traceback", "yaml"], "enclosing_function": "test_wrapper_openai_provider", "extracted_code": "# Source: mini_agent/llm/llm_wrapper.py\nclass LLMClient:\n \"\"\"LLM Client wrapper supporting multiple providers.\n\n This class provides a unified interface for different LLM providers.\n It automatically instantiates the correct underlying client based on\n the provider parameter.\n\n For MiniMax API (api.minimax.io or api.minimaxi.com), it appends the\n appropriate endpoint suffix based on provider:\n - anthropic: /anthropic\n - openai: /v1\n\n For third-party APIs, it uses the api_base as-is.\n \"\"\"\n\n # MiniMax API domains that need automatic suffix handling\n MINIMAX_DOMAINS = (\"api.minimax.io\", \"api.minimaxi.com\")\n\n def __init__(\n self,\n api_key: str,\n provider: LLMProvider = LLMProvider.ANTHROPIC,\n api_base: str = \"https://api.minimaxi.com\",\n model: str = \"MiniMax-M2.5\",\n retry_config: RetryConfig | None = None,\n ):\n \"\"\"Initialize LLM client with specified provider.\n\n Args:\n api_key: API key for authentication\n provider: LLM provider (anthropic or openai)\n api_base: Base URL for the API (default: https://api.minimaxi.com)\n For MiniMax API, suffix is auto-appended based on provider.\n For third-party APIs (e.g., https://api.siliconflow.cn/v1), used as-is.\n model: Model name to use\n retry_config: Optional retry configuration\n \"\"\"\n self.provider = provider\n self.api_key = api_key\n self.model = model\n self.retry_config = retry_config or RetryConfig()\n\n # Normalize api_base (remove trailing slash)\n api_base = api_base.rstrip(\"/\")\n\n # Check if this is a MiniMax API endpoint\n is_minimax = any(domain in api_base for domain in self.MINIMAX_DOMAINS)\n\n if is_minimax:\n # For MiniMax API, ensure correct suffix based on provider\n # Strip any existing suffix first\n api_base = api_base.replace(\"/anthropic\", \"\").replace(\"/v1\", \"\")\n if provider == LLMProvider.ANTHROPIC:\n full_api_base = f\"{api_base}/anthropic\"\n elif provider == LLMProvider.OPENAI:\n full_api_base = f\"{api_base}/v1\"\n else:\n raise ValueError(f\"Unsupported provider: {provider}\")\n else:\n # For third-party APIs, use api_base as-is\n full_api_base = api_base\n\n self.api_base = full_api_base\n\n # Instantiate the appropriate client\n self._client: LLMClientBase\n if provider == LLMProvider.ANTHROPIC:\n self._client = AnthropicClient(\n api_key=api_key,\n api_base=full_api_base,\n model=model,\n retry_config=retry_config,\n )\n elif provider == LLMProvider.OPENAI:\n self._client = OpenAIClient(\n api_key=api_key,\n api_base=full_api_base,\n model=model,\n retry_config=retry_config,\n )\n else:\n raise ValueError(f\"Unsupported provider: {provider}\")\n\n logger.info(\"Initialized LLM client with provider: %s, api_base: %s\", provider, full_api_base)\n\n @property\n def retry_callback(self):\n \"\"\"Get retry callback.\"\"\"\n return self._client.retry_callback\n\n @retry_callback.setter\n def retry_callback(self, value):\n \"\"\"Set retry callback.\"\"\"\n self._client.retry_callback = value\n\n async def generate(\n self,\n messages: list[Message],\n tools: list | None = None,\n ) -> LLMResponse:\n \"\"\"Generate response from LLM.\n\n Args:\n messages: List of conversation messages\n tools: Optional list of Tool objects or dicts\n\n Returns:\n LLMResponse containing the generated content\n \"\"\"\n return await self._client.generate(messages, tools)\n\n\n# Source: mini_agent/schema/schema.py\nclass LLMProvider(str, Enum):\n \"\"\"LLM provider types.\"\"\"\n\n ANTHROPIC = \"anthropic\"\n OPENAI = \"openai\"\n\nclass Message(BaseModel):\n \"\"\"Chat message.\"\"\"\n\n role: str # \"system\", \"user\", \"assistant\", \"tool\"\n content: str | list[dict[str, Any]] # Can be string or list of content blocks\n thinking: str | None = None # Extended thinking content for assistant messages\n tool_calls: list[ToolCall] | None = None\n tool_call_id: str | None = None\n name: str | None = None", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 4464}, "tests/test_llm.py::31": {"resolved_imports": ["mini_agent/llm/llm_wrapper.py", "mini_agent/schema/schema.py"], "used_names": ["LLMClient", "LLMProvider", "Message", "Path", "asyncio", "pytest", "traceback", "yaml"], "enclosing_function": "test_wrapper_anthropic_provider", "extracted_code": "# Source: mini_agent/llm/llm_wrapper.py\nclass LLMClient:\n \"\"\"LLM Client wrapper supporting multiple providers.\n\n This class provides a unified interface for different LLM providers.\n It automatically instantiates the correct underlying client based on\n the provider parameter.\n\n For MiniMax API (api.minimax.io or api.minimaxi.com), it appends the\n appropriate endpoint suffix based on provider:\n - anthropic: /anthropic\n - openai: /v1\n\n For third-party APIs, it uses the api_base as-is.\n \"\"\"\n\n # MiniMax API domains that need automatic suffix handling\n MINIMAX_DOMAINS = (\"api.minimax.io\", \"api.minimaxi.com\")\n\n def __init__(\n self,\n api_key: str,\n provider: LLMProvider = LLMProvider.ANTHROPIC,\n api_base: str = \"https://api.minimaxi.com\",\n model: str = \"MiniMax-M2.5\",\n retry_config: RetryConfig | None = None,\n ):\n \"\"\"Initialize LLM client with specified provider.\n\n Args:\n api_key: API key for authentication\n provider: LLM provider (anthropic or openai)\n api_base: Base URL for the API (default: https://api.minimaxi.com)\n For MiniMax API, suffix is auto-appended based on provider.\n For third-party APIs (e.g., https://api.siliconflow.cn/v1), used as-is.\n model: Model name to use\n retry_config: Optional retry configuration\n \"\"\"\n self.provider = provider\n self.api_key = api_key\n self.model = model\n self.retry_config = retry_config or RetryConfig()\n\n # Normalize api_base (remove trailing slash)\n api_base = api_base.rstrip(\"/\")\n\n # Check if this is a MiniMax API endpoint\n is_minimax = any(domain in api_base for domain in self.MINIMAX_DOMAINS)\n\n if is_minimax:\n # For MiniMax API, ensure correct suffix based on provider\n # Strip any existing suffix first\n api_base = api_base.replace(\"/anthropic\", \"\").replace(\"/v1\", \"\")\n if provider == LLMProvider.ANTHROPIC:\n full_api_base = f\"{api_base}/anthropic\"\n elif provider == LLMProvider.OPENAI:\n full_api_base = f\"{api_base}/v1\"\n else:\n raise ValueError(f\"Unsupported provider: {provider}\")\n else:\n # For third-party APIs, use api_base as-is\n full_api_base = api_base\n\n self.api_base = full_api_base\n\n # Instantiate the appropriate client\n self._client: LLMClientBase\n if provider == LLMProvider.ANTHROPIC:\n self._client = AnthropicClient(\n api_key=api_key,\n api_base=full_api_base,\n model=model,\n retry_config=retry_config,\n )\n elif provider == LLMProvider.OPENAI:\n self._client = OpenAIClient(\n api_key=api_key,\n api_base=full_api_base,\n model=model,\n retry_config=retry_config,\n )\n else:\n raise ValueError(f\"Unsupported provider: {provider}\")\n\n logger.info(\"Initialized LLM client with provider: %s, api_base: %s\", provider, full_api_base)\n\n @property\n def retry_callback(self):\n \"\"\"Get retry callback.\"\"\"\n return self._client.retry_callback\n\n @retry_callback.setter\n def retry_callback(self, value):\n \"\"\"Set retry callback.\"\"\"\n self._client.retry_callback = value\n\n async def generate(\n self,\n messages: list[Message],\n tools: list | None = None,\n ) -> LLMResponse:\n \"\"\"Generate response from LLM.\n\n Args:\n messages: List of conversation messages\n tools: Optional list of Tool objects or dicts\n\n Returns:\n LLMResponse containing the generated content\n \"\"\"\n return await self._client.generate(messages, tools)\n\n\n# Source: mini_agent/schema/schema.py\nclass LLMProvider(str, Enum):\n \"\"\"LLM provider types.\"\"\"\n\n ANTHROPIC = \"anthropic\"\n OPENAI = \"openai\"\n\nclass Message(BaseModel):\n \"\"\"Chat message.\"\"\"\n\n role: str # \"system\", \"user\", \"assistant\", \"tool\"\n content: str | list[dict[str, Any]] # Can be string or list of content blocks\n thinking: str | None = None # Extended thinking content for assistant messages\n tool_calls: list[ToolCall] | None = None\n tool_call_id: str | None = None\n name: str | None = None", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 4464}, "tests/test_llm_clients.py::152": {"resolved_imports": ["mini_agent/llm/anthropic_client.py", "mini_agent/llm/openai_client.py", "mini_agent/retry.py", "mini_agent/schema/schema.py"], "used_names": ["AnthropicClient", "Message", "asyncio", "pytest", "traceback"], "enclosing_function": "test_anthropic_tool_calling", "extracted_code": "# Source: mini_agent/llm/anthropic_client.py\nclass AnthropicClient(LLMClientBase):\n \"\"\"LLM client using Anthropic's protocol.\n\n This client uses the official Anthropic SDK and supports:\n - Extended thinking content\n - Tool calling\n - Retry logic\n \"\"\"\n\n def __init__(\n self,\n api_key: str,\n api_base: str = \"https://api.minimaxi.com/anthropic\",\n model: str = \"MiniMax-M2.5\",\n retry_config: RetryConfig | None = None,\n ):\n \"\"\"Initialize Anthropic client.\n\n Args:\n api_key: API key for authentication\n api_base: Base URL for the API (default: MiniMax Anthropic endpoint)\n model: Model name to use (default: MiniMax-M2.5)\n retry_config: Optional retry configuration\n \"\"\"\n super().__init__(api_key, api_base, model, retry_config)\n\n # Initialize Anthropic async client\n self.client = anthropic.AsyncAnthropic(\n base_url=api_base,\n api_key=api_key,\n default_headers={\"Authorization\": f\"Bearer {api_key}\"},\n )\n\n async def _make_api_request(\n self,\n system_message: str | None,\n api_messages: list[dict[str, Any]],\n tools: list[Any] | None = None,\n ) -> anthropic.types.Message:\n \"\"\"Execute API request (core method that can be retried).\n\n Args:\n system_message: Optional system message\n api_messages: List of messages in Anthropic format\n tools: Optional list of tools\n\n Returns:\n Anthropic Message response\n\n Raises:\n Exception: API call failed\n \"\"\"\n params = {\n \"model\": self.model,\n \"max_tokens\": 16384,\n \"messages\": api_messages,\n }\n\n if system_message:\n params[\"system\"] = system_message\n\n if tools:\n params[\"tools\"] = self._convert_tools(tools)\n\n # Use Anthropic SDK's async messages.create\n response = await self.client.messages.create(**params)\n return response\n\n def _convert_tools(self, tools: list[Any]) -> list[dict[str, Any]]:\n \"\"\"Convert tools to Anthropic format.\n\n Anthropic tool format:\n {\n \"name\": \"tool_name\",\n \"description\": \"Tool description\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {...},\n \"required\": [...]\n }\n }\n\n Args:\n tools: List of Tool objects or dicts\n\n Returns:\n List of tools in Anthropic dict format\n \"\"\"\n result = []\n for tool in tools:\n if isinstance(tool, dict):\n result.append(tool)\n elif hasattr(tool, \"to_schema\"):\n # Tool object with to_schema method\n result.append(tool.to_schema())\n else:\n raise TypeError(f\"Unsupported tool type: {type(tool)}\")\n return result\n\n def _convert_messages(self, messages: list[Message]) -> tuple[str | None, list[dict[str, Any]]]:\n \"\"\"Convert internal messages to Anthropic format.\n\n Args:\n messages: List of internal Message objects\n\n Returns:\n Tuple of (system_message, api_messages)\n \"\"\"\n system_message = None\n api_messages = []\n\n for msg in messages:\n if msg.role == \"system\":\n system_message = msg.content\n continue\n\n # For user and assistant messages\n if msg.role in [\"user\", \"assistant\"]:\n # Handle assistant messages with thinking or tool calls\n if msg.role == \"assistant\" and (msg.thinking or msg.tool_calls):\n # Build content blocks for assistant with thinking and/or tool calls\n content_blocks = []\n\n # Add thinking block if present\n if msg.thinking:\n content_blocks.append({\"type\": \"thinking\", \"thinking\": msg.thinking})\n\n # Add text content if present\n if msg.content:\n content_blocks.append({\"type\": \"text\", \"text\": msg.content})\n\n # Add tool use blocks\n if msg.tool_calls:\n for tool_call in msg.tool_calls:\n content_blocks.append(\n {\n \"type\": \"tool_use\",\n \"id\": tool_call.id,\n \"name\": tool_call.function.name,\n \"input\": tool_call.function.arguments,\n }\n )\n\n api_messages.append({\"role\": \"assistant\", \"content\": content_blocks})\n else:\n api_messages.append({\"role\": msg.role, \"content\": msg.content})\n\n # For tool result messages\n elif msg.role == \"tool\":\n # Anthropic uses user role with tool_result content blocks\n api_messages.append(\n {\n \"role\": \"user\",\n \"content\": [\n {\n \"type\": \"tool_result\",\n \"tool_use_id\": msg.tool_call_id,\n \"content\": msg.content,\n }\n ],\n }\n )\n\n return system_message, api_messages\n\n def _prepare_request(\n self,\n messages: list[Message],\n tools: list[Any] | None = None,\n ) -> dict[str, Any]:\n \"\"\"Prepare the request for Anthropic API.\n\n Args:\n messages: List of conversation messages\n tools: Optional list of available tools\n\n Returns:\n Dictionary containing request parameters\n \"\"\"\n system_message, api_messages = self._convert_messages(messages)\n\n return {\n \"system_message\": system_message,\n \"api_messages\": api_messages,\n \"tools\": tools,\n }\n\n def _parse_response(self, response: anthropic.types.Message) -> LLMResponse:\n \"\"\"Parse Anthropic response into LLMResponse.\n\n Args:\n response: Anthropic Message response\n\n Returns:\n LLMResponse object\n \"\"\"\n # Extract text content, thinking, and tool calls\n text_content = \"\"\n thinking_content = \"\"\n tool_calls = []\n\n for block in response.content:\n if block.type == \"text\":\n text_content += block.text\n elif block.type == \"thinking\":\n thinking_content += block.thinking\n elif block.type == \"tool_use\":\n # Parse Anthropic tool_use block\n tool_calls.append(\n ToolCall(\n id=block.id,\n type=\"function\",\n function=FunctionCall(\n name=block.name,\n arguments=block.input,\n ),\n )\n )\n\n # Extract token usage from response\n # Anthropic usage includes: input_tokens, output_tokens, cache_read_input_tokens, cache_creation_input_tokens\n usage = None\n if hasattr(response, \"usage\") and response.usage:\n input_tokens = response.usage.input_tokens or 0\n output_tokens = response.usage.output_tokens or 0\n cache_read_tokens = getattr(response.usage, \"cache_read_input_tokens\", 0) or 0\n cache_creation_tokens = getattr(response.usage, \"cache_creation_input_tokens\", 0) or 0\n total_input_tokens = input_tokens + cache_read_tokens + cache_creation_tokens\n usage = TokenUsage(\n prompt_tokens=total_input_tokens,\n completion_tokens=output_tokens,\n total_tokens=total_input_tokens + output_tokens,\n )\n\n return LLMResponse(\n content=text_content,\n thinking=thinking_content if thinking_content else None,\n tool_calls=tool_calls if tool_calls else None,\n finish_reason=response.stop_reason or \"stop\",\n usage=usage,\n )\n\n async def generate(\n self,\n messages: list[Message],\n tools: list[Any] | None = None,\n ) -> LLMResponse:\n \"\"\"Generate response from Anthropic LLM.\n\n Args:\n messages: List of conversation messages\n tools: Optional list of available tools\n\n Returns:\n LLMResponse containing the generated content\n \"\"\"\n # Prepare request\n request_params = self._prepare_request(messages, tools)\n\n # Make API request with retry logic\n if self.retry_config.enabled:\n # Apply retry logic\n retry_decorator = async_retry(config=self.retry_config, on_retry=self.retry_callback)\n api_call = retry_decorator(self._make_api_request)\n response = await api_call(\n request_params[\"system_message\"],\n request_params[\"api_messages\"],\n request_params[\"tools\"],\n )\n else:\n # Don't use retry\n response = await self._make_api_request(\n request_params[\"system_message\"],\n request_params[\"api_messages\"],\n request_params[\"tools\"],\n )\n\n # Parse and return response\n return self._parse_response(response)\n\n\n# Source: mini_agent/schema/schema.py\nclass Message(BaseModel):\n \"\"\"Chat message.\"\"\"\n\n role: str # \"system\", \"user\", \"assistant\", \"tool\"\n content: str | list[dict[str, Any]] # Can be string or list of content blocks\n thinking: str | None = None # Extended thinking content for assistant messages\n tool_calls: list[ToolCall] | None = None\n tool_call_id: str | None = None\n name: str | None = None", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 10119}, "tests/test_llm_clients.py::153": {"resolved_imports": ["mini_agent/llm/anthropic_client.py", "mini_agent/llm/openai_client.py", "mini_agent/retry.py", "mini_agent/schema/schema.py"], "used_names": ["AnthropicClient", "Message", "asyncio", "pytest", "traceback"], "enclosing_function": "test_anthropic_tool_calling", "extracted_code": "# Source: mini_agent/llm/anthropic_client.py\nclass AnthropicClient(LLMClientBase):\n \"\"\"LLM client using Anthropic's protocol.\n\n This client uses the official Anthropic SDK and supports:\n - Extended thinking content\n - Tool calling\n - Retry logic\n \"\"\"\n\n def __init__(\n self,\n api_key: str,\n api_base: str = \"https://api.minimaxi.com/anthropic\",\n model: str = \"MiniMax-M2.5\",\n retry_config: RetryConfig | None = None,\n ):\n \"\"\"Initialize Anthropic client.\n\n Args:\n api_key: API key for authentication\n api_base: Base URL for the API (default: MiniMax Anthropic endpoint)\n model: Model name to use (default: MiniMax-M2.5)\n retry_config: Optional retry configuration\n \"\"\"\n super().__init__(api_key, api_base, model, retry_config)\n\n # Initialize Anthropic async client\n self.client = anthropic.AsyncAnthropic(\n base_url=api_base,\n api_key=api_key,\n default_headers={\"Authorization\": f\"Bearer {api_key}\"},\n )\n\n async def _make_api_request(\n self,\n system_message: str | None,\n api_messages: list[dict[str, Any]],\n tools: list[Any] | None = None,\n ) -> anthropic.types.Message:\n \"\"\"Execute API request (core method that can be retried).\n\n Args:\n system_message: Optional system message\n api_messages: List of messages in Anthropic format\n tools: Optional list of tools\n\n Returns:\n Anthropic Message response\n\n Raises:\n Exception: API call failed\n \"\"\"\n params = {\n \"model\": self.model,\n \"max_tokens\": 16384,\n \"messages\": api_messages,\n }\n\n if system_message:\n params[\"system\"] = system_message\n\n if tools:\n params[\"tools\"] = self._convert_tools(tools)\n\n # Use Anthropic SDK's async messages.create\n response = await self.client.messages.create(**params)\n return response\n\n def _convert_tools(self, tools: list[Any]) -> list[dict[str, Any]]:\n \"\"\"Convert tools to Anthropic format.\n\n Anthropic tool format:\n {\n \"name\": \"tool_name\",\n \"description\": \"Tool description\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {...},\n \"required\": [...]\n }\n }\n\n Args:\n tools: List of Tool objects or dicts\n\n Returns:\n List of tools in Anthropic dict format\n \"\"\"\n result = []\n for tool in tools:\n if isinstance(tool, dict):\n result.append(tool)\n elif hasattr(tool, \"to_schema\"):\n # Tool object with to_schema method\n result.append(tool.to_schema())\n else:\n raise TypeError(f\"Unsupported tool type: {type(tool)}\")\n return result\n\n def _convert_messages(self, messages: list[Message]) -> tuple[str | None, list[dict[str, Any]]]:\n \"\"\"Convert internal messages to Anthropic format.\n\n Args:\n messages: List of internal Message objects\n\n Returns:\n Tuple of (system_message, api_messages)\n \"\"\"\n system_message = None\n api_messages = []\n\n for msg in messages:\n if msg.role == \"system\":\n system_message = msg.content\n continue\n\n # For user and assistant messages\n if msg.role in [\"user\", \"assistant\"]:\n # Handle assistant messages with thinking or tool calls\n if msg.role == \"assistant\" and (msg.thinking or msg.tool_calls):\n # Build content blocks for assistant with thinking and/or tool calls\n content_blocks = []\n\n # Add thinking block if present\n if msg.thinking:\n content_blocks.append({\"type\": \"thinking\", \"thinking\": msg.thinking})\n\n # Add text content if present\n if msg.content:\n content_blocks.append({\"type\": \"text\", \"text\": msg.content})\n\n # Add tool use blocks\n if msg.tool_calls:\n for tool_call in msg.tool_calls:\n content_blocks.append(\n {\n \"type\": \"tool_use\",\n \"id\": tool_call.id,\n \"name\": tool_call.function.name,\n \"input\": tool_call.function.arguments,\n }\n )\n\n api_messages.append({\"role\": \"assistant\", \"content\": content_blocks})\n else:\n api_messages.append({\"role\": msg.role, \"content\": msg.content})\n\n # For tool result messages\n elif msg.role == \"tool\":\n # Anthropic uses user role with tool_result content blocks\n api_messages.append(\n {\n \"role\": \"user\",\n \"content\": [\n {\n \"type\": \"tool_result\",\n \"tool_use_id\": msg.tool_call_id,\n \"content\": msg.content,\n }\n ],\n }\n )\n\n return system_message, api_messages\n\n def _prepare_request(\n self,\n messages: list[Message],\n tools: list[Any] | None = None,\n ) -> dict[str, Any]:\n \"\"\"Prepare the request for Anthropic API.\n\n Args:\n messages: List of conversation messages\n tools: Optional list of available tools\n\n Returns:\n Dictionary containing request parameters\n \"\"\"\n system_message, api_messages = self._convert_messages(messages)\n\n return {\n \"system_message\": system_message,\n \"api_messages\": api_messages,\n \"tools\": tools,\n }\n\n def _parse_response(self, response: anthropic.types.Message) -> LLMResponse:\n \"\"\"Parse Anthropic response into LLMResponse.\n\n Args:\n response: Anthropic Message response\n\n Returns:\n LLMResponse object\n \"\"\"\n # Extract text content, thinking, and tool calls\n text_content = \"\"\n thinking_content = \"\"\n tool_calls = []\n\n for block in response.content:\n if block.type == \"text\":\n text_content += block.text\n elif block.type == \"thinking\":\n thinking_content += block.thinking\n elif block.type == \"tool_use\":\n # Parse Anthropic tool_use block\n tool_calls.append(\n ToolCall(\n id=block.id,\n type=\"function\",\n function=FunctionCall(\n name=block.name,\n arguments=block.input,\n ),\n )\n )\n\n # Extract token usage from response\n # Anthropic usage includes: input_tokens, output_tokens, cache_read_input_tokens, cache_creation_input_tokens\n usage = None\n if hasattr(response, \"usage\") and response.usage:\n input_tokens = response.usage.input_tokens or 0\n output_tokens = response.usage.output_tokens or 0\n cache_read_tokens = getattr(response.usage, \"cache_read_input_tokens\", 0) or 0\n cache_creation_tokens = getattr(response.usage, \"cache_creation_input_tokens\", 0) or 0\n total_input_tokens = input_tokens + cache_read_tokens + cache_creation_tokens\n usage = TokenUsage(\n prompt_tokens=total_input_tokens,\n completion_tokens=output_tokens,\n total_tokens=total_input_tokens + output_tokens,\n )\n\n return LLMResponse(\n content=text_content,\n thinking=thinking_content if thinking_content else None,\n tool_calls=tool_calls if tool_calls else None,\n finish_reason=response.stop_reason or \"stop\",\n usage=usage,\n )\n\n async def generate(\n self,\n messages: list[Message],\n tools: list[Any] | None = None,\n ) -> LLMResponse:\n \"\"\"Generate response from Anthropic LLM.\n\n Args:\n messages: List of conversation messages\n tools: Optional list of available tools\n\n Returns:\n LLMResponse containing the generated content\n \"\"\"\n # Prepare request\n request_params = self._prepare_request(messages, tools)\n\n # Make API request with retry logic\n if self.retry_config.enabled:\n # Apply retry logic\n retry_decorator = async_retry(config=self.retry_config, on_retry=self.retry_callback)\n api_call = retry_decorator(self._make_api_request)\n response = await api_call(\n request_params[\"system_message\"],\n request_params[\"api_messages\"],\n request_params[\"tools\"],\n )\n else:\n # Don't use retry\n response = await self._make_api_request(\n request_params[\"system_message\"],\n request_params[\"api_messages\"],\n request_params[\"tools\"],\n )\n\n # Parse and return response\n return self._parse_response(response)\n\n\n# Source: mini_agent/schema/schema.py\nclass Message(BaseModel):\n \"\"\"Chat message.\"\"\"\n\n role: str # \"system\", \"user\", \"assistant\", \"tool\"\n content: str | list[dict[str, Any]] # Can be string or list of content blocks\n thinking: str | None = None # Extended thinking content for assistant messages\n tool_calls: list[ToolCall] | None = None\n tool_call_id: str | None = None\n name: str | None = None", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 10119}, "tests/test_markdown_links.py::55": {"resolved_imports": ["mini_agent/tools/skill_loader.py"], "used_names": ["Path", "SkillLoader", "tempfile"], "enclosing_function": "test_markdown_link_processing", "extracted_code": "# Source: mini_agent/tools/skill_loader.py\nclass SkillLoader:\n \"\"\"Skill loader\"\"\"\n\n def __init__(self, skills_dir: str = \"./skills\"):\n \"\"\"\n Initialize Skill Loader\n\n Args:\n skills_dir: Skills directory path\n \"\"\"\n self.skills_dir = Path(skills_dir)\n self.loaded_skills: Dict[str, Skill] = {}\n\n def load_skill(self, skill_path: Path) -> Optional[Skill]:\n \"\"\"\n Load single skill from SKILL.md file\n\n Args:\n skill_path: SKILL.md file path\n\n Returns:\n Skill object, or None if loading fails\n \"\"\"\n try:\n content = skill_path.read_text(encoding=\"utf-8\")\n\n # Parse YAML frontmatter\n frontmatter_match = re.match(r\"^---\\n(.*?)\\n---\\n(.*)$\", content, re.DOTALL)\n\n if not frontmatter_match:\n print(f\"⚠️ {skill_path} missing YAML frontmatter\")\n return None\n\n frontmatter_text = frontmatter_match.group(1)\n skill_content = frontmatter_match.group(2).strip()\n\n # Parse YAML\n try:\n frontmatter = yaml.safe_load(frontmatter_text)\n except yaml.YAMLError as e:\n print(f\"❌ Failed to parse YAML frontmatter: {e}\")\n return None\n\n # Required fields\n if \"name\" not in frontmatter or \"description\" not in frontmatter:\n print(f\"⚠️ {skill_path} missing required fields (name or description)\")\n return None\n\n # Get skill directory (parent of SKILL.md)\n skill_dir = skill_path.parent\n\n # Replace relative paths in content with absolute paths\n # This ensures scripts and resources can be found from any working directory\n processed_content = self._process_skill_paths(skill_content, skill_dir)\n\n # Create Skill object\n skill = Skill(\n name=frontmatter[\"name\"],\n description=frontmatter[\"description\"],\n content=processed_content,\n license=frontmatter.get(\"license\"),\n allowed_tools=frontmatter.get(\"allowed-tools\"),\n metadata=frontmatter.get(\"metadata\"),\n skill_path=skill_path,\n )\n\n return skill\n\n except Exception as e:\n print(f\"❌ Failed to load skill ({skill_path}): {e}\")\n return None\n\n def _process_skill_paths(self, content: str, skill_dir: Path) -> str:\n \"\"\"\n Process skill content to replace relative paths with absolute paths.\n\n Supports Progressive Disclosure Level 3+: converts relative file references\n to absolute paths so Agent can easily read nested resources.\n\n Args:\n content: Original skill content\n skill_dir: Skill directory path\n\n Returns:\n Processed content with absolute paths\n \"\"\"\n import re\n\n # Pattern 1: Directory-based paths (scripts/, references/, assets/)\n # See https://agentskills.io/specification#optional-directories\n def replace_dir_path(match):\n prefix = match.group(1) # e.g., \"python \" or \"`\"\n rel_path = match.group(2) # e.g., \"scripts/with_server.py\"\n\n abs_path = skill_dir / rel_path\n if abs_path.exists():\n return f\"{prefix}{abs_path}\"\n return match.group(0)\n\n pattern_dirs = r\"(python\\s+|`)((?:scripts|references|assets)/[^\\s`\\)]+)\"\n content = re.sub(pattern_dirs, replace_dir_path, content)\n\n # Pattern 2: Direct markdown/document references (forms.md, reference.md, etc.)\n # Matches phrases like \"see reference.md\" or \"read forms.md\"\n def replace_doc_path(match):\n prefix = match.group(1) # e.g., \"see \", \"read \"\n filename = match.group(2) # e.g., \"reference.md\"\n suffix = match.group(3) # e.g., punctuation\n\n abs_path = skill_dir / filename\n if abs_path.exists():\n # Add helpful instruction for Agent\n return f\"{prefix}`{abs_path}` (use read_file to access){suffix}\"\n return match.group(0)\n\n # Match patterns like: \"see reference.md\" or \"read forms.md\"\n pattern_docs = r\"(see|read|refer to|check)\\s+([a-zA-Z0-9_-]+\\.(?:md|txt|json|yaml))([.,;\\s])\"\n content = re.sub(pattern_docs, replace_doc_path, content, flags=re.IGNORECASE)\n\n # Pattern 3: Markdown links - supports multiple formats:\n # - [`filename.md`](filename.md) - simple filename\n # - [text](./reference/file.md) - relative path with ./\n # - [text](scripts/file.js) - directory-based path\n # Matches patterns like: \"Read [`docx-js.md`](docx-js.md)\" or \"Load [Guide](./reference/guide.md)\"\n def replace_markdown_link(match):\n prefix = match.group(1) if match.group(1) else \"\" # e.g., \"Read \", \"Load \", or empty\n link_text = match.group(2) # e.g., \"`docx-js.md`\" or \"Guide\"\n filepath = match.group(3) # e.g., \"docx-js.md\", \"./reference/file.md\", \"scripts/file.js\"\n\n # Remove leading ./ if present\n clean_path = filepath[2:] if filepath.startswith(\"./\") else filepath\n\n abs_path = skill_dir / clean_path\n if abs_path.exists():\n # Preserve the link text style (with or without backticks)\n return f\"{prefix}[{link_text}](`{abs_path}`) (use read_file to access)\"\n return match.group(0)\n\n # Match markdown link patterns with optional prefix words\n # Captures: (optional prefix word) [link text] (complete file path including ./)\n pattern_markdown = (\n r\"(?:(Read|See|Check|Refer to|Load|View)\\s+)?\\[(`?[^`\\]]+`?)\\]\\(((?:\\./)?[^)]+\\.(?:md|txt|json|yaml|js|py|html))\\)\"\n )\n content = re.sub(pattern_markdown, replace_markdown_link, content, flags=re.IGNORECASE)\n\n return content\n\n def discover_skills(self) -> List[Skill]:\n \"\"\"\n Discover and load all skills in the skills directory\n\n Returns:\n List of Skills\n \"\"\"\n skills = []\n\n if not self.skills_dir.exists():\n print(f\"⚠️ Skills directory does not exist: {self.skills_dir}\")\n return skills\n\n # Recursively find all SKILL.md files\n for skill_file in self.skills_dir.rglob(\"SKILL.md\"):\n skill = self.load_skill(skill_file)\n if skill:\n skills.append(skill)\n self.loaded_skills[skill.name] = skill\n\n return skills\n\n def get_skill(self, name: str) -> Optional[Skill]:\n \"\"\"\n Get loaded skill\n\n Args:\n name: Skill name\n\n Returns:\n Skill object, or None if not found\n \"\"\"\n return self.loaded_skills.get(name)\n\n def list_skills(self) -> List[str]:\n \"\"\"\n List all loaded skill names\n\n Returns:\n List of skill names\n \"\"\"\n return list(self.loaded_skills.keys())\n\n def get_skills_metadata_prompt(self) -> str:\n \"\"\"\n Generate prompt containing ONLY metadata (name + description) for all skills.\n This implements Progressive Disclosure - Level 1.\n\n Returns:\n Metadata-only prompt string\n \"\"\"\n if not self.loaded_skills:\n return \"\"\n\n prompt_parts = [\"## Available Skills\\n\"]\n prompt_parts.append(\"You have access to specialized skills. Each skill provides expert guidance for specific tasks.\\n\")\n prompt_parts.append(\"Load a skill's full content using the appropriate skill tool when needed.\\n\")\n\n # List all skills with their descriptions\n for skill in self.loaded_skills.values():\n prompt_parts.append(f\"- `{skill.name}`: {skill.description}\")\n\n return \"\\n\".join(prompt_parts)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 7912}, "tests/test_markdown_links.py::71": {"resolved_imports": ["mini_agent/tools/skill_loader.py"], "used_names": ["Path", "SkillLoader", "tempfile"], "enclosing_function": "test_markdown_link_processing", "extracted_code": "# Source: mini_agent/tools/skill_loader.py\nclass SkillLoader:\n \"\"\"Skill loader\"\"\"\n\n def __init__(self, skills_dir: str = \"./skills\"):\n \"\"\"\n Initialize Skill Loader\n\n Args:\n skills_dir: Skills directory path\n \"\"\"\n self.skills_dir = Path(skills_dir)\n self.loaded_skills: Dict[str, Skill] = {}\n\n def load_skill(self, skill_path: Path) -> Optional[Skill]:\n \"\"\"\n Load single skill from SKILL.md file\n\n Args:\n skill_path: SKILL.md file path\n\n Returns:\n Skill object, or None if loading fails\n \"\"\"\n try:\n content = skill_path.read_text(encoding=\"utf-8\")\n\n # Parse YAML frontmatter\n frontmatter_match = re.match(r\"^---\\n(.*?)\\n---\\n(.*)$\", content, re.DOTALL)\n\n if not frontmatter_match:\n print(f\"⚠️ {skill_path} missing YAML frontmatter\")\n return None\n\n frontmatter_text = frontmatter_match.group(1)\n skill_content = frontmatter_match.group(2).strip()\n\n # Parse YAML\n try:\n frontmatter = yaml.safe_load(frontmatter_text)\n except yaml.YAMLError as e:\n print(f\"❌ Failed to parse YAML frontmatter: {e}\")\n return None\n\n # Required fields\n if \"name\" not in frontmatter or \"description\" not in frontmatter:\n print(f\"⚠️ {skill_path} missing required fields (name or description)\")\n return None\n\n # Get skill directory (parent of SKILL.md)\n skill_dir = skill_path.parent\n\n # Replace relative paths in content with absolute paths\n # This ensures scripts and resources can be found from any working directory\n processed_content = self._process_skill_paths(skill_content, skill_dir)\n\n # Create Skill object\n skill = Skill(\n name=frontmatter[\"name\"],\n description=frontmatter[\"description\"],\n content=processed_content,\n license=frontmatter.get(\"license\"),\n allowed_tools=frontmatter.get(\"allowed-tools\"),\n metadata=frontmatter.get(\"metadata\"),\n skill_path=skill_path,\n )\n\n return skill\n\n except Exception as e:\n print(f\"❌ Failed to load skill ({skill_path}): {e}\")\n return None\n\n def _process_skill_paths(self, content: str, skill_dir: Path) -> str:\n \"\"\"\n Process skill content to replace relative paths with absolute paths.\n\n Supports Progressive Disclosure Level 3+: converts relative file references\n to absolute paths so Agent can easily read nested resources.\n\n Args:\n content: Original skill content\n skill_dir: Skill directory path\n\n Returns:\n Processed content with absolute paths\n \"\"\"\n import re\n\n # Pattern 1: Directory-based paths (scripts/, references/, assets/)\n # See https://agentskills.io/specification#optional-directories\n def replace_dir_path(match):\n prefix = match.group(1) # e.g., \"python \" or \"`\"\n rel_path = match.group(2) # e.g., \"scripts/with_server.py\"\n\n abs_path = skill_dir / rel_path\n if abs_path.exists():\n return f\"{prefix}{abs_path}\"\n return match.group(0)\n\n pattern_dirs = r\"(python\\s+|`)((?:scripts|references|assets)/[^\\s`\\)]+)\"\n content = re.sub(pattern_dirs, replace_dir_path, content)\n\n # Pattern 2: Direct markdown/document references (forms.md, reference.md, etc.)\n # Matches phrases like \"see reference.md\" or \"read forms.md\"\n def replace_doc_path(match):\n prefix = match.group(1) # e.g., \"see \", \"read \"\n filename = match.group(2) # e.g., \"reference.md\"\n suffix = match.group(3) # e.g., punctuation\n\n abs_path = skill_dir / filename\n if abs_path.exists():\n # Add helpful instruction for Agent\n return f\"{prefix}`{abs_path}` (use read_file to access){suffix}\"\n return match.group(0)\n\n # Match patterns like: \"see reference.md\" or \"read forms.md\"\n pattern_docs = r\"(see|read|refer to|check)\\s+([a-zA-Z0-9_-]+\\.(?:md|txt|json|yaml))([.,;\\s])\"\n content = re.sub(pattern_docs, replace_doc_path, content, flags=re.IGNORECASE)\n\n # Pattern 3: Markdown links - supports multiple formats:\n # - [`filename.md`](filename.md) - simple filename\n # - [text](./reference/file.md) - relative path with ./\n # - [text](scripts/file.js) - directory-based path\n # Matches patterns like: \"Read [`docx-js.md`](docx-js.md)\" or \"Load [Guide](./reference/guide.md)\"\n def replace_markdown_link(match):\n prefix = match.group(1) if match.group(1) else \"\" # e.g., \"Read \", \"Load \", or empty\n link_text = match.group(2) # e.g., \"`docx-js.md`\" or \"Guide\"\n filepath = match.group(3) # e.g., \"docx-js.md\", \"./reference/file.md\", \"scripts/file.js\"\n\n # Remove leading ./ if present\n clean_path = filepath[2:] if filepath.startswith(\"./\") else filepath\n\n abs_path = skill_dir / clean_path\n if abs_path.exists():\n # Preserve the link text style (with or without backticks)\n return f\"{prefix}[{link_text}](`{abs_path}`) (use read_file to access)\"\n return match.group(0)\n\n # Match markdown link patterns with optional prefix words\n # Captures: (optional prefix word) [link text] (complete file path including ./)\n pattern_markdown = (\n r\"(?:(Read|See|Check|Refer to|Load|View)\\s+)?\\[(`?[^`\\]]+`?)\\]\\(((?:\\./)?[^)]+\\.(?:md|txt|json|yaml|js|py|html))\\)\"\n )\n content = re.sub(pattern_markdown, replace_markdown_link, content, flags=re.IGNORECASE)\n\n return content\n\n def discover_skills(self) -> List[Skill]:\n \"\"\"\n Discover and load all skills in the skills directory\n\n Returns:\n List of Skills\n \"\"\"\n skills = []\n\n if not self.skills_dir.exists():\n print(f\"⚠️ Skills directory does not exist: {self.skills_dir}\")\n return skills\n\n # Recursively find all SKILL.md files\n for skill_file in self.skills_dir.rglob(\"SKILL.md\"):\n skill = self.load_skill(skill_file)\n if skill:\n skills.append(skill)\n self.loaded_skills[skill.name] = skill\n\n return skills\n\n def get_skill(self, name: str) -> Optional[Skill]:\n \"\"\"\n Get loaded skill\n\n Args:\n name: Skill name\n\n Returns:\n Skill object, or None if not found\n \"\"\"\n return self.loaded_skills.get(name)\n\n def list_skills(self) -> List[str]:\n \"\"\"\n List all loaded skill names\n\n Returns:\n List of skill names\n \"\"\"\n return list(self.loaded_skills.keys())\n\n def get_skills_metadata_prompt(self) -> str:\n \"\"\"\n Generate prompt containing ONLY metadata (name + description) for all skills.\n This implements Progressive Disclosure - Level 1.\n\n Returns:\n Metadata-only prompt string\n \"\"\"\n if not self.loaded_skills:\n return \"\"\n\n prompt_parts = [\"## Available Skills\\n\"]\n prompt_parts.append(\"You have access to specialized skills. Each skill provides expert guidance for specific tasks.\\n\")\n prompt_parts.append(\"Load a skill's full content using the appropriate skill tool when needed.\\n\")\n\n # List all skills with their descriptions\n for skill in self.loaded_skills.values():\n prompt_parts.append(f\"- `{skill.name}`: {skill.description}\")\n\n return \"\\n\".join(prompt_parts)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 7912}, "tests/test_markdown_links.py::59": {"resolved_imports": ["mini_agent/tools/skill_loader.py"], "used_names": ["Path", "SkillLoader", "tempfile"], "enclosing_function": "test_markdown_link_processing", "extracted_code": "# Source: mini_agent/tools/skill_loader.py\nclass SkillLoader:\n \"\"\"Skill loader\"\"\"\n\n def __init__(self, skills_dir: str = \"./skills\"):\n \"\"\"\n Initialize Skill Loader\n\n Args:\n skills_dir: Skills directory path\n \"\"\"\n self.skills_dir = Path(skills_dir)\n self.loaded_skills: Dict[str, Skill] = {}\n\n def load_skill(self, skill_path: Path) -> Optional[Skill]:\n \"\"\"\n Load single skill from SKILL.md file\n\n Args:\n skill_path: SKILL.md file path\n\n Returns:\n Skill object, or None if loading fails\n \"\"\"\n try:\n content = skill_path.read_text(encoding=\"utf-8\")\n\n # Parse YAML frontmatter\n frontmatter_match = re.match(r\"^---\\n(.*?)\\n---\\n(.*)$\", content, re.DOTALL)\n\n if not frontmatter_match:\n print(f\"⚠️ {skill_path} missing YAML frontmatter\")\n return None\n\n frontmatter_text = frontmatter_match.group(1)\n skill_content = frontmatter_match.group(2).strip()\n\n # Parse YAML\n try:\n frontmatter = yaml.safe_load(frontmatter_text)\n except yaml.YAMLError as e:\n print(f\"❌ Failed to parse YAML frontmatter: {e}\")\n return None\n\n # Required fields\n if \"name\" not in frontmatter or \"description\" not in frontmatter:\n print(f\"⚠️ {skill_path} missing required fields (name or description)\")\n return None\n\n # Get skill directory (parent of SKILL.md)\n skill_dir = skill_path.parent\n\n # Replace relative paths in content with absolute paths\n # This ensures scripts and resources can be found from any working directory\n processed_content = self._process_skill_paths(skill_content, skill_dir)\n\n # Create Skill object\n skill = Skill(\n name=frontmatter[\"name\"],\n description=frontmatter[\"description\"],\n content=processed_content,\n license=frontmatter.get(\"license\"),\n allowed_tools=frontmatter.get(\"allowed-tools\"),\n metadata=frontmatter.get(\"metadata\"),\n skill_path=skill_path,\n )\n\n return skill\n\n except Exception as e:\n print(f\"❌ Failed to load skill ({skill_path}): {e}\")\n return None\n\n def _process_skill_paths(self, content: str, skill_dir: Path) -> str:\n \"\"\"\n Process skill content to replace relative paths with absolute paths.\n\n Supports Progressive Disclosure Level 3+: converts relative file references\n to absolute paths so Agent can easily read nested resources.\n\n Args:\n content: Original skill content\n skill_dir: Skill directory path\n\n Returns:\n Processed content with absolute paths\n \"\"\"\n import re\n\n # Pattern 1: Directory-based paths (scripts/, references/, assets/)\n # See https://agentskills.io/specification#optional-directories\n def replace_dir_path(match):\n prefix = match.group(1) # e.g., \"python \" or \"`\"\n rel_path = match.group(2) # e.g., \"scripts/with_server.py\"\n\n abs_path = skill_dir / rel_path\n if abs_path.exists():\n return f\"{prefix}{abs_path}\"\n return match.group(0)\n\n pattern_dirs = r\"(python\\s+|`)((?:scripts|references|assets)/[^\\s`\\)]+)\"\n content = re.sub(pattern_dirs, replace_dir_path, content)\n\n # Pattern 2: Direct markdown/document references (forms.md, reference.md, etc.)\n # Matches phrases like \"see reference.md\" or \"read forms.md\"\n def replace_doc_path(match):\n prefix = match.group(1) # e.g., \"see \", \"read \"\n filename = match.group(2) # e.g., \"reference.md\"\n suffix = match.group(3) # e.g., punctuation\n\n abs_path = skill_dir / filename\n if abs_path.exists():\n # Add helpful instruction for Agent\n return f\"{prefix}`{abs_path}` (use read_file to access){suffix}\"\n return match.group(0)\n\n # Match patterns like: \"see reference.md\" or \"read forms.md\"\n pattern_docs = r\"(see|read|refer to|check)\\s+([a-zA-Z0-9_-]+\\.(?:md|txt|json|yaml))([.,;\\s])\"\n content = re.sub(pattern_docs, replace_doc_path, content, flags=re.IGNORECASE)\n\n # Pattern 3: Markdown links - supports multiple formats:\n # - [`filename.md`](filename.md) - simple filename\n # - [text](./reference/file.md) - relative path with ./\n # - [text](scripts/file.js) - directory-based path\n # Matches patterns like: \"Read [`docx-js.md`](docx-js.md)\" or \"Load [Guide](./reference/guide.md)\"\n def replace_markdown_link(match):\n prefix = match.group(1) if match.group(1) else \"\" # e.g., \"Read \", \"Load \", or empty\n link_text = match.group(2) # e.g., \"`docx-js.md`\" or \"Guide\"\n filepath = match.group(3) # e.g., \"docx-js.md\", \"./reference/file.md\", \"scripts/file.js\"\n\n # Remove leading ./ if present\n clean_path = filepath[2:] if filepath.startswith(\"./\") else filepath\n\n abs_path = skill_dir / clean_path\n if abs_path.exists():\n # Preserve the link text style (with or without backticks)\n return f\"{prefix}[{link_text}](`{abs_path}`) (use read_file to access)\"\n return match.group(0)\n\n # Match markdown link patterns with optional prefix words\n # Captures: (optional prefix word) [link text] (complete file path including ./)\n pattern_markdown = (\n r\"(?:(Read|See|Check|Refer to|Load|View)\\s+)?\\[(`?[^`\\]]+`?)\\]\\(((?:\\./)?[^)]+\\.(?:md|txt|json|yaml|js|py|html))\\)\"\n )\n content = re.sub(pattern_markdown, replace_markdown_link, content, flags=re.IGNORECASE)\n\n return content\n\n def discover_skills(self) -> List[Skill]:\n \"\"\"\n Discover and load all skills in the skills directory\n\n Returns:\n List of Skills\n \"\"\"\n skills = []\n\n if not self.skills_dir.exists():\n print(f\"⚠️ Skills directory does not exist: {self.skills_dir}\")\n return skills\n\n # Recursively find all SKILL.md files\n for skill_file in self.skills_dir.rglob(\"SKILL.md\"):\n skill = self.load_skill(skill_file)\n if skill:\n skills.append(skill)\n self.loaded_skills[skill.name] = skill\n\n return skills\n\n def get_skill(self, name: str) -> Optional[Skill]:\n \"\"\"\n Get loaded skill\n\n Args:\n name: Skill name\n\n Returns:\n Skill object, or None if not found\n \"\"\"\n return self.loaded_skills.get(name)\n\n def list_skills(self) -> List[str]:\n \"\"\"\n List all loaded skill names\n\n Returns:\n List of skill names\n \"\"\"\n return list(self.loaded_skills.keys())\n\n def get_skills_metadata_prompt(self) -> str:\n \"\"\"\n Generate prompt containing ONLY metadata (name + description) for all skills.\n This implements Progressive Disclosure - Level 1.\n\n Returns:\n Metadata-only prompt string\n \"\"\"\n if not self.loaded_skills:\n return \"\"\n\n prompt_parts = [\"## Available Skills\\n\"]\n prompt_parts.append(\"You have access to specialized skills. Each skill provides expert guidance for specific tasks.\\n\")\n prompt_parts.append(\"Load a skill's full content using the appropriate skill tool when needed.\\n\")\n\n # List all skills with their descriptions\n for skill in self.loaded_skills.values():\n prompt_parts.append(f\"- `{skill.name}`: {skill.description}\")\n\n return \"\\n\".join(prompt_parts)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 7912}, "tests/test_mcp.py::409": {"resolved_imports": ["mini_agent/tools/mcp_loader.py"], "used_names": ["asyncio", "cleanup_mcp_connections", "load_mcp_tools_async", "pytest"], "enclosing_function": "test_git_mcp_loading", "extracted_code": "# Source: mini_agent/tools/mcp_loader.py\nasync def load_mcp_tools_async(config_path: str = \"mcp.json\") -> list[Tool]:\n \"\"\"\n Load MCP tools from config file.\n\n This function:\n 1. Reads the MCP config file (with fallback to mcp-example.json)\n 2. Connects to each server (STDIO or URL-based)\n 3. Fetches tool definitions\n 4. Wraps them as Tool objects\n\n Supported config formats:\n - STDIO: {\"command\": \"...\", \"args\": [...], \"env\": {...}}\n - URL-based: {\"url\": \"https://...\", \"type\": \"sse|http|streamable_http\", \"headers\": {...}}\n\n Per-server timeout overrides (optional):\n - \"connect_timeout\": float - Connection timeout in seconds\n - \"execute_timeout\": float - Tool execution timeout in seconds\n - \"sse_read_timeout\": float - SSE read timeout in seconds\n\n Note:\n - If mcp.json is not found, will automatically fallback to mcp-example.json\n - User-specific mcp.json should be created by copying mcp-example.json\n\n Args:\n config_path: Path to MCP configuration file (default: \"mcp.json\")\n\n Returns:\n List of Tool objects representing MCP tools\n \"\"\"\n global _mcp_connections\n\n config_file = _resolve_mcp_config_path(config_path)\n\n if config_file is None:\n print(f\"MCP config not found: {config_path}\")\n return []\n\n try:\n with open(config_file, encoding=\"utf-8\") as f:\n config = json.load(f)\n\n mcp_servers = config.get(\"mcpServers\", {})\n\n if not mcp_servers:\n print(\"No MCP servers configured\")\n return []\n\n all_tools = []\n\n # Connect to each enabled server\n for server_name, server_config in mcp_servers.items():\n if server_config.get(\"disabled\", False):\n print(f\"Skipping disabled server: {server_name}\")\n continue\n\n conn_type = _determine_connection_type(server_config)\n url = server_config.get(\"url\")\n command = server_config.get(\"command\")\n\n # Validate config\n if conn_type == \"stdio\" and not command:\n print(f\"No command specified for STDIO server: {server_name}\")\n continue\n if conn_type in (\"sse\", \"http\", \"streamable_http\") and not url:\n print(f\"No url specified for {conn_type.upper()} server: {server_name}\")\n continue\n\n connection = MCPServerConnection(\n name=server_name,\n connection_type=conn_type,\n command=command,\n args=server_config.get(\"args\", []),\n env=server_config.get(\"env\", {}),\n url=url,\n headers=server_config.get(\"headers\", {}),\n # Per-server timeout overrides from mcp.json\n connect_timeout=server_config.get(\"connect_timeout\"),\n execute_timeout=server_config.get(\"execute_timeout\"),\n sse_read_timeout=server_config.get(\"sse_read_timeout\"),\n )\n success = await connection.connect()\n\n if success:\n _mcp_connections.append(connection)\n all_tools.extend(connection.tools)\n\n print(f\"\\nTotal MCP tools loaded: {len(all_tools)}\")\n\n return all_tools\n\n except Exception as e:\n print(f\"Error loading MCP config: {e}\")\n import traceback\n\n traceback.print_exc()\n return []\n\nasync def cleanup_mcp_connections():\n \"\"\"Clean up all MCP connections.\"\"\"\n global _mcp_connections\n for connection in _mcp_connections:\n await connection.disconnect()\n _mcp_connections.clear()", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 3622}, "tests/test_mcp.py::136": {"resolved_imports": ["mini_agent/tools/mcp_loader.py"], "used_names": ["MCPServerConnection"], "enclosing_function": "test_default_values", "extracted_code": "# Source: mini_agent/tools/mcp_loader.py\nclass MCPServerConnection:\n \"\"\"Manages connection to a single MCP server (STDIO or URL-based) with timeout handling.\"\"\"\n\n def __init__(\n self,\n name: str,\n connection_type: ConnectionType = \"stdio\",\n # STDIO params\n command: str | None = None,\n args: list[str] | None = None,\n env: dict[str, str] | None = None,\n # URL-based params\n url: str | None = None,\n headers: dict[str, str] | None = None,\n # Timeout overrides (per-server)\n connect_timeout: float | None = None,\n execute_timeout: float | None = None,\n sse_read_timeout: float | None = None,\n ):\n self.name = name\n self.connection_type = connection_type\n # STDIO\n self.command = command\n self.args = args or []\n self.env = env or {}\n # URL-based\n self.url = url\n self.headers = headers or {}\n # Timeout settings (per-server overrides)\n self.connect_timeout = connect_timeout\n self.execute_timeout = execute_timeout\n self.sse_read_timeout = sse_read_timeout\n # Connection state\n self.session: ClientSession | None = None\n self.exit_stack: AsyncExitStack | None = None\n self.tools: list[MCPTool] = []\n\n def _get_connect_timeout(self) -> float:\n \"\"\"Get effective connect timeout.\"\"\"\n return self.connect_timeout or _default_timeout_config.connect_timeout\n\n def _get_sse_read_timeout(self) -> float:\n \"\"\"Get effective SSE read timeout.\"\"\"\n return self.sse_read_timeout or _default_timeout_config.sse_read_timeout\n\n def _get_execute_timeout(self) -> float:\n \"\"\"Get effective execute timeout.\"\"\"\n return self.execute_timeout or _default_timeout_config.execute_timeout\n\n async def connect(self) -> bool:\n \"\"\"Connect to the MCP server with timeout protection.\"\"\"\n connect_timeout = self._get_connect_timeout()\n\n try:\n self.exit_stack = AsyncExitStack()\n\n # Wrap connection with timeout\n async with asyncio.timeout(connect_timeout):\n if self.connection_type == \"stdio\":\n read_stream, write_stream = await self._connect_stdio()\n elif self.connection_type == \"sse\":\n read_stream, write_stream = await self._connect_sse()\n else: # http / streamable_http\n read_stream, write_stream = await self._connect_streamable_http()\n\n # Enter client session context\n session = await self.exit_stack.enter_async_context(ClientSession(read_stream, write_stream))\n self.session = session\n\n # Initialize the session\n await session.initialize()\n\n # List available tools\n tools_list = await session.list_tools()\n\n # Wrap each tool with execute timeout\n execute_timeout = self._get_execute_timeout()\n for tool in tools_list.tools:\n parameters = tool.inputSchema if hasattr(tool, \"inputSchema\") else {}\n mcp_tool = MCPTool(\n name=tool.name,\n description=tool.description or \"\",\n parameters=parameters,\n session=session,\n execute_timeout=execute_timeout,\n )\n self.tools.append(mcp_tool)\n\n conn_info = self.url if self.url else self.command\n print(f\"✓ Connected to MCP server '{self.name}' ({self.connection_type}: {conn_info}) - loaded {len(self.tools)} tools\")\n for tool in self.tools:\n desc = tool.description[:60] if len(tool.description) > 60 else tool.description\n print(f\" - {tool.name}: {desc}...\")\n return True\n\n except TimeoutError:\n print(f\"✗ Connection to MCP server '{self.name}' timed out after {connect_timeout}s\")\n if self.exit_stack:\n await self.exit_stack.aclose()\n self.exit_stack = None\n return False\n\n except Exception as e:\n print(f\"✗ Failed to connect to MCP server '{self.name}': {e}\")\n if self.exit_stack:\n await self.exit_stack.aclose()\n self.exit_stack = None\n import traceback\n\n traceback.print_exc()\n return False\n\n async def _connect_stdio(self):\n \"\"\"Connect via STDIO transport.\"\"\"\n server_params = StdioServerParameters(command=self.command, args=self.args, env=self.env if self.env else None)\n return await self.exit_stack.enter_async_context(stdio_client(server_params))\n\n async def _connect_sse(self):\n \"\"\"Connect via SSE transport with timeout parameters.\"\"\"\n connect_timeout = self._get_connect_timeout()\n sse_read_timeout = self._get_sse_read_timeout()\n\n return await self.exit_stack.enter_async_context(\n sse_client(\n url=self.url,\n headers=self.headers if self.headers else None,\n timeout=connect_timeout,\n sse_read_timeout=sse_read_timeout,\n )\n )\n\n async def _connect_streamable_http(self):\n \"\"\"Connect via Streamable HTTP transport with timeout parameters.\"\"\"\n connect_timeout = self._get_connect_timeout()\n sse_read_timeout = self._get_sse_read_timeout()\n\n # streamablehttp_client returns (read, write, get_session_id)\n read_stream, write_stream, _ = await self.exit_stack.enter_async_context(\n streamablehttp_client(\n url=self.url,\n headers=self.headers if self.headers else None,\n timeout=connect_timeout,\n sse_read_timeout=sse_read_timeout,\n )\n )\n return read_stream, write_stream\n\n async def disconnect(self):\n \"\"\"Properly disconnect from the MCP server.\"\"\"\n if self.exit_stack:\n try:\n await self.exit_stack.aclose()\n except Exception:\n # anyio cancel scope may raise RuntimeError or ExceptionGroup\n # when stdio_client's task group is closed from a different\n # task context during shutdown.\n pass\n finally:\n self.exit_stack = None\n self.session = None", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 6464}, "tests/test_mcp.py::137": {"resolved_imports": ["mini_agent/tools/mcp_loader.py"], "used_names": ["MCPServerConnection"], "enclosing_function": "test_default_values", "extracted_code": "# Source: mini_agent/tools/mcp_loader.py\nclass MCPServerConnection:\n \"\"\"Manages connection to a single MCP server (STDIO or URL-based) with timeout handling.\"\"\"\n\n def __init__(\n self,\n name: str,\n connection_type: ConnectionType = \"stdio\",\n # STDIO params\n command: str | None = None,\n args: list[str] | None = None,\n env: dict[str, str] | None = None,\n # URL-based params\n url: str | None = None,\n headers: dict[str, str] | None = None,\n # Timeout overrides (per-server)\n connect_timeout: float | None = None,\n execute_timeout: float | None = None,\n sse_read_timeout: float | None = None,\n ):\n self.name = name\n self.connection_type = connection_type\n # STDIO\n self.command = command\n self.args = args or []\n self.env = env or {}\n # URL-based\n self.url = url\n self.headers = headers or {}\n # Timeout settings (per-server overrides)\n self.connect_timeout = connect_timeout\n self.execute_timeout = execute_timeout\n self.sse_read_timeout = sse_read_timeout\n # Connection state\n self.session: ClientSession | None = None\n self.exit_stack: AsyncExitStack | None = None\n self.tools: list[MCPTool] = []\n\n def _get_connect_timeout(self) -> float:\n \"\"\"Get effective connect timeout.\"\"\"\n return self.connect_timeout or _default_timeout_config.connect_timeout\n\n def _get_sse_read_timeout(self) -> float:\n \"\"\"Get effective SSE read timeout.\"\"\"\n return self.sse_read_timeout or _default_timeout_config.sse_read_timeout\n\n def _get_execute_timeout(self) -> float:\n \"\"\"Get effective execute timeout.\"\"\"\n return self.execute_timeout or _default_timeout_config.execute_timeout\n\n async def connect(self) -> bool:\n \"\"\"Connect to the MCP server with timeout protection.\"\"\"\n connect_timeout = self._get_connect_timeout()\n\n try:\n self.exit_stack = AsyncExitStack()\n\n # Wrap connection with timeout\n async with asyncio.timeout(connect_timeout):\n if self.connection_type == \"stdio\":\n read_stream, write_stream = await self._connect_stdio()\n elif self.connection_type == \"sse\":\n read_stream, write_stream = await self._connect_sse()\n else: # http / streamable_http\n read_stream, write_stream = await self._connect_streamable_http()\n\n # Enter client session context\n session = await self.exit_stack.enter_async_context(ClientSession(read_stream, write_stream))\n self.session = session\n\n # Initialize the session\n await session.initialize()\n\n # List available tools\n tools_list = await session.list_tools()\n\n # Wrap each tool with execute timeout\n execute_timeout = self._get_execute_timeout()\n for tool in tools_list.tools:\n parameters = tool.inputSchema if hasattr(tool, \"inputSchema\") else {}\n mcp_tool = MCPTool(\n name=tool.name,\n description=tool.description or \"\",\n parameters=parameters,\n session=session,\n execute_timeout=execute_timeout,\n )\n self.tools.append(mcp_tool)\n\n conn_info = self.url if self.url else self.command\n print(f\"✓ Connected to MCP server '{self.name}' ({self.connection_type}: {conn_info}) - loaded {len(self.tools)} tools\")\n for tool in self.tools:\n desc = tool.description[:60] if len(tool.description) > 60 else tool.description\n print(f\" - {tool.name}: {desc}...\")\n return True\n\n except TimeoutError:\n print(f\"✗ Connection to MCP server '{self.name}' timed out after {connect_timeout}s\")\n if self.exit_stack:\n await self.exit_stack.aclose()\n self.exit_stack = None\n return False\n\n except Exception as e:\n print(f\"✗ Failed to connect to MCP server '{self.name}': {e}\")\n if self.exit_stack:\n await self.exit_stack.aclose()\n self.exit_stack = None\n import traceback\n\n traceback.print_exc()\n return False\n\n async def _connect_stdio(self):\n \"\"\"Connect via STDIO transport.\"\"\"\n server_params = StdioServerParameters(command=self.command, args=self.args, env=self.env if self.env else None)\n return await self.exit_stack.enter_async_context(stdio_client(server_params))\n\n async def _connect_sse(self):\n \"\"\"Connect via SSE transport with timeout parameters.\"\"\"\n connect_timeout = self._get_connect_timeout()\n sse_read_timeout = self._get_sse_read_timeout()\n\n return await self.exit_stack.enter_async_context(\n sse_client(\n url=self.url,\n headers=self.headers if self.headers else None,\n timeout=connect_timeout,\n sse_read_timeout=sse_read_timeout,\n )\n )\n\n async def _connect_streamable_http(self):\n \"\"\"Connect via Streamable HTTP transport with timeout parameters.\"\"\"\n connect_timeout = self._get_connect_timeout()\n sse_read_timeout = self._get_sse_read_timeout()\n\n # streamablehttp_client returns (read, write, get_session_id)\n read_stream, write_stream, _ = await self.exit_stack.enter_async_context(\n streamablehttp_client(\n url=self.url,\n headers=self.headers if self.headers else None,\n timeout=connect_timeout,\n sse_read_timeout=sse_read_timeout,\n )\n )\n return read_stream, write_stream\n\n async def disconnect(self):\n \"\"\"Properly disconnect from the MCP server.\"\"\"\n if self.exit_stack:\n try:\n await self.exit_stack.aclose()\n except Exception:\n # anyio cancel scope may raise RuntimeError or ExceptionGroup\n # when stdio_client's task group is closed from a different\n # task context during shutdown.\n pass\n finally:\n self.exit_stack = None\n self.session = None", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 6464}, "tests/test_mcp.py::177": {"resolved_imports": ["mini_agent/tools/mcp_loader.py"], "used_names": ["MCPTimeoutConfig"], "enclosing_function": "test_custom_timeout_config", "extracted_code": "# Source: mini_agent/tools/mcp_loader.py\nclass MCPTimeoutConfig:\n \"\"\"MCP timeout configuration.\"\"\"\n\n connect_timeout: float = 10.0 # Connection timeout (seconds)\n execute_timeout: float = 60.0 # Tool execution timeout (seconds)\n sse_read_timeout: float = 120.0", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 274}, "tests/test_mcp.py::105": {"resolved_imports": ["mini_agent/tools/mcp_loader.py"], "used_names": ["MCPServerConnection"], "enclosing_function": "test_stdio_connection_init", "extracted_code": "# Source: mini_agent/tools/mcp_loader.py\nclass MCPServerConnection:\n \"\"\"Manages connection to a single MCP server (STDIO or URL-based) with timeout handling.\"\"\"\n\n def __init__(\n self,\n name: str,\n connection_type: ConnectionType = \"stdio\",\n # STDIO params\n command: str | None = None,\n args: list[str] | None = None,\n env: dict[str, str] | None = None,\n # URL-based params\n url: str | None = None,\n headers: dict[str, str] | None = None,\n # Timeout overrides (per-server)\n connect_timeout: float | None = None,\n execute_timeout: float | None = None,\n sse_read_timeout: float | None = None,\n ):\n self.name = name\n self.connection_type = connection_type\n # STDIO\n self.command = command\n self.args = args or []\n self.env = env or {}\n # URL-based\n self.url = url\n self.headers = headers or {}\n # Timeout settings (per-server overrides)\n self.connect_timeout = connect_timeout\n self.execute_timeout = execute_timeout\n self.sse_read_timeout = sse_read_timeout\n # Connection state\n self.session: ClientSession | None = None\n self.exit_stack: AsyncExitStack | None = None\n self.tools: list[MCPTool] = []\n\n def _get_connect_timeout(self) -> float:\n \"\"\"Get effective connect timeout.\"\"\"\n return self.connect_timeout or _default_timeout_config.connect_timeout\n\n def _get_sse_read_timeout(self) -> float:\n \"\"\"Get effective SSE read timeout.\"\"\"\n return self.sse_read_timeout or _default_timeout_config.sse_read_timeout\n\n def _get_execute_timeout(self) -> float:\n \"\"\"Get effective execute timeout.\"\"\"\n return self.execute_timeout or _default_timeout_config.execute_timeout\n\n async def connect(self) -> bool:\n \"\"\"Connect to the MCP server with timeout protection.\"\"\"\n connect_timeout = self._get_connect_timeout()\n\n try:\n self.exit_stack = AsyncExitStack()\n\n # Wrap connection with timeout\n async with asyncio.timeout(connect_timeout):\n if self.connection_type == \"stdio\":\n read_stream, write_stream = await self._connect_stdio()\n elif self.connection_type == \"sse\":\n read_stream, write_stream = await self._connect_sse()\n else: # http / streamable_http\n read_stream, write_stream = await self._connect_streamable_http()\n\n # Enter client session context\n session = await self.exit_stack.enter_async_context(ClientSession(read_stream, write_stream))\n self.session = session\n\n # Initialize the session\n await session.initialize()\n\n # List available tools\n tools_list = await session.list_tools()\n\n # Wrap each tool with execute timeout\n execute_timeout = self._get_execute_timeout()\n for tool in tools_list.tools:\n parameters = tool.inputSchema if hasattr(tool, \"inputSchema\") else {}\n mcp_tool = MCPTool(\n name=tool.name,\n description=tool.description or \"\",\n parameters=parameters,\n session=session,\n execute_timeout=execute_timeout,\n )\n self.tools.append(mcp_tool)\n\n conn_info = self.url if self.url else self.command\n print(f\"✓ Connected to MCP server '{self.name}' ({self.connection_type}: {conn_info}) - loaded {len(self.tools)} tools\")\n for tool in self.tools:\n desc = tool.description[:60] if len(tool.description) > 60 else tool.description\n print(f\" - {tool.name}: {desc}...\")\n return True\n\n except TimeoutError:\n print(f\"✗ Connection to MCP server '{self.name}' timed out after {connect_timeout}s\")\n if self.exit_stack:\n await self.exit_stack.aclose()\n self.exit_stack = None\n return False\n\n except Exception as e:\n print(f\"✗ Failed to connect to MCP server '{self.name}': {e}\")\n if self.exit_stack:\n await self.exit_stack.aclose()\n self.exit_stack = None\n import traceback\n\n traceback.print_exc()\n return False\n\n async def _connect_stdio(self):\n \"\"\"Connect via STDIO transport.\"\"\"\n server_params = StdioServerParameters(command=self.command, args=self.args, env=self.env if self.env else None)\n return await self.exit_stack.enter_async_context(stdio_client(server_params))\n\n async def _connect_sse(self):\n \"\"\"Connect via SSE transport with timeout parameters.\"\"\"\n connect_timeout = self._get_connect_timeout()\n sse_read_timeout = self._get_sse_read_timeout()\n\n return await self.exit_stack.enter_async_context(\n sse_client(\n url=self.url,\n headers=self.headers if self.headers else None,\n timeout=connect_timeout,\n sse_read_timeout=sse_read_timeout,\n )\n )\n\n async def _connect_streamable_http(self):\n \"\"\"Connect via Streamable HTTP transport with timeout parameters.\"\"\"\n connect_timeout = self._get_connect_timeout()\n sse_read_timeout = self._get_sse_read_timeout()\n\n # streamablehttp_client returns (read, write, get_session_id)\n read_stream, write_stream, _ = await self.exit_stack.enter_async_context(\n streamablehttp_client(\n url=self.url,\n headers=self.headers if self.headers else None,\n timeout=connect_timeout,\n sse_read_timeout=sse_read_timeout,\n )\n )\n return read_stream, write_stream\n\n async def disconnect(self):\n \"\"\"Properly disconnect from the MCP server.\"\"\"\n if self.exit_stack:\n try:\n await self.exit_stack.aclose()\n except Exception:\n # anyio cancel scope may raise RuntimeError or ExceptionGroup\n # when stdio_client's task group is closed from a different\n # task context during shutdown.\n pass\n finally:\n self.exit_stack = None\n self.session = None", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 6464}, "tests/test_mcp.py::150": {"resolved_imports": ["mini_agent/tools/mcp_loader.py"], "used_names": ["MCPServerConnection"], "enclosing_function": "test_timeout_overrides", "extracted_code": "# Source: mini_agent/tools/mcp_loader.py\nclass MCPServerConnection:\n \"\"\"Manages connection to a single MCP server (STDIO or URL-based) with timeout handling.\"\"\"\n\n def __init__(\n self,\n name: str,\n connection_type: ConnectionType = \"stdio\",\n # STDIO params\n command: str | None = None,\n args: list[str] | None = None,\n env: dict[str, str] | None = None,\n # URL-based params\n url: str | None = None,\n headers: dict[str, str] | None = None,\n # Timeout overrides (per-server)\n connect_timeout: float | None = None,\n execute_timeout: float | None = None,\n sse_read_timeout: float | None = None,\n ):\n self.name = name\n self.connection_type = connection_type\n # STDIO\n self.command = command\n self.args = args or []\n self.env = env or {}\n # URL-based\n self.url = url\n self.headers = headers or {}\n # Timeout settings (per-server overrides)\n self.connect_timeout = connect_timeout\n self.execute_timeout = execute_timeout\n self.sse_read_timeout = sse_read_timeout\n # Connection state\n self.session: ClientSession | None = None\n self.exit_stack: AsyncExitStack | None = None\n self.tools: list[MCPTool] = []\n\n def _get_connect_timeout(self) -> float:\n \"\"\"Get effective connect timeout.\"\"\"\n return self.connect_timeout or _default_timeout_config.connect_timeout\n\n def _get_sse_read_timeout(self) -> float:\n \"\"\"Get effective SSE read timeout.\"\"\"\n return self.sse_read_timeout or _default_timeout_config.sse_read_timeout\n\n def _get_execute_timeout(self) -> float:\n \"\"\"Get effective execute timeout.\"\"\"\n return self.execute_timeout or _default_timeout_config.execute_timeout\n\n async def connect(self) -> bool:\n \"\"\"Connect to the MCP server with timeout protection.\"\"\"\n connect_timeout = self._get_connect_timeout()\n\n try:\n self.exit_stack = AsyncExitStack()\n\n # Wrap connection with timeout\n async with asyncio.timeout(connect_timeout):\n if self.connection_type == \"stdio\":\n read_stream, write_stream = await self._connect_stdio()\n elif self.connection_type == \"sse\":\n read_stream, write_stream = await self._connect_sse()\n else: # http / streamable_http\n read_stream, write_stream = await self._connect_streamable_http()\n\n # Enter client session context\n session = await self.exit_stack.enter_async_context(ClientSession(read_stream, write_stream))\n self.session = session\n\n # Initialize the session\n await session.initialize()\n\n # List available tools\n tools_list = await session.list_tools()\n\n # Wrap each tool with execute timeout\n execute_timeout = self._get_execute_timeout()\n for tool in tools_list.tools:\n parameters = tool.inputSchema if hasattr(tool, \"inputSchema\") else {}\n mcp_tool = MCPTool(\n name=tool.name,\n description=tool.description or \"\",\n parameters=parameters,\n session=session,\n execute_timeout=execute_timeout,\n )\n self.tools.append(mcp_tool)\n\n conn_info = self.url if self.url else self.command\n print(f\"✓ Connected to MCP server '{self.name}' ({self.connection_type}: {conn_info}) - loaded {len(self.tools)} tools\")\n for tool in self.tools:\n desc = tool.description[:60] if len(tool.description) > 60 else tool.description\n print(f\" - {tool.name}: {desc}...\")\n return True\n\n except TimeoutError:\n print(f\"✗ Connection to MCP server '{self.name}' timed out after {connect_timeout}s\")\n if self.exit_stack:\n await self.exit_stack.aclose()\n self.exit_stack = None\n return False\n\n except Exception as e:\n print(f\"✗ Failed to connect to MCP server '{self.name}': {e}\")\n if self.exit_stack:\n await self.exit_stack.aclose()\n self.exit_stack = None\n import traceback\n\n traceback.print_exc()\n return False\n\n async def _connect_stdio(self):\n \"\"\"Connect via STDIO transport.\"\"\"\n server_params = StdioServerParameters(command=self.command, args=self.args, env=self.env if self.env else None)\n return await self.exit_stack.enter_async_context(stdio_client(server_params))\n\n async def _connect_sse(self):\n \"\"\"Connect via SSE transport with timeout parameters.\"\"\"\n connect_timeout = self._get_connect_timeout()\n sse_read_timeout = self._get_sse_read_timeout()\n\n return await self.exit_stack.enter_async_context(\n sse_client(\n url=self.url,\n headers=self.headers if self.headers else None,\n timeout=connect_timeout,\n sse_read_timeout=sse_read_timeout,\n )\n )\n\n async def _connect_streamable_http(self):\n \"\"\"Connect via Streamable HTTP transport with timeout parameters.\"\"\"\n connect_timeout = self._get_connect_timeout()\n sse_read_timeout = self._get_sse_read_timeout()\n\n # streamablehttp_client returns (read, write, get_session_id)\n read_stream, write_stream, _ = await self.exit_stack.enter_async_context(\n streamablehttp_client(\n url=self.url,\n headers=self.headers if self.headers else None,\n timeout=connect_timeout,\n sse_read_timeout=sse_read_timeout,\n )\n )\n return read_stream, write_stream\n\n async def disconnect(self):\n \"\"\"Properly disconnect from the MCP server.\"\"\"\n if self.exit_stack:\n try:\n await self.exit_stack.aclose()\n except Exception:\n # anyio cancel scope may raise RuntimeError or ExceptionGroup\n # when stdio_client's task group is closed from a different\n # task context during shutdown.\n pass\n finally:\n self.exit_stack = None\n self.session = None", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 6464}, "tests/test_mcp.py::151": {"resolved_imports": ["mini_agent/tools/mcp_loader.py"], "used_names": ["MCPServerConnection"], "enclosing_function": "test_timeout_overrides", "extracted_code": "# Source: mini_agent/tools/mcp_loader.py\nclass MCPServerConnection:\n \"\"\"Manages connection to a single MCP server (STDIO or URL-based) with timeout handling.\"\"\"\n\n def __init__(\n self,\n name: str,\n connection_type: ConnectionType = \"stdio\",\n # STDIO params\n command: str | None = None,\n args: list[str] | None = None,\n env: dict[str, str] | None = None,\n # URL-based params\n url: str | None = None,\n headers: dict[str, str] | None = None,\n # Timeout overrides (per-server)\n connect_timeout: float | None = None,\n execute_timeout: float | None = None,\n sse_read_timeout: float | None = None,\n ):\n self.name = name\n self.connection_type = connection_type\n # STDIO\n self.command = command\n self.args = args or []\n self.env = env or {}\n # URL-based\n self.url = url\n self.headers = headers or {}\n # Timeout settings (per-server overrides)\n self.connect_timeout = connect_timeout\n self.execute_timeout = execute_timeout\n self.sse_read_timeout = sse_read_timeout\n # Connection state\n self.session: ClientSession | None = None\n self.exit_stack: AsyncExitStack | None = None\n self.tools: list[MCPTool] = []\n\n def _get_connect_timeout(self) -> float:\n \"\"\"Get effective connect timeout.\"\"\"\n return self.connect_timeout or _default_timeout_config.connect_timeout\n\n def _get_sse_read_timeout(self) -> float:\n \"\"\"Get effective SSE read timeout.\"\"\"\n return self.sse_read_timeout or _default_timeout_config.sse_read_timeout\n\n def _get_execute_timeout(self) -> float:\n \"\"\"Get effective execute timeout.\"\"\"\n return self.execute_timeout or _default_timeout_config.execute_timeout\n\n async def connect(self) -> bool:\n \"\"\"Connect to the MCP server with timeout protection.\"\"\"\n connect_timeout = self._get_connect_timeout()\n\n try:\n self.exit_stack = AsyncExitStack()\n\n # Wrap connection with timeout\n async with asyncio.timeout(connect_timeout):\n if self.connection_type == \"stdio\":\n read_stream, write_stream = await self._connect_stdio()\n elif self.connection_type == \"sse\":\n read_stream, write_stream = await self._connect_sse()\n else: # http / streamable_http\n read_stream, write_stream = await self._connect_streamable_http()\n\n # Enter client session context\n session = await self.exit_stack.enter_async_context(ClientSession(read_stream, write_stream))\n self.session = session\n\n # Initialize the session\n await session.initialize()\n\n # List available tools\n tools_list = await session.list_tools()\n\n # Wrap each tool with execute timeout\n execute_timeout = self._get_execute_timeout()\n for tool in tools_list.tools:\n parameters = tool.inputSchema if hasattr(tool, \"inputSchema\") else {}\n mcp_tool = MCPTool(\n name=tool.name,\n description=tool.description or \"\",\n parameters=parameters,\n session=session,\n execute_timeout=execute_timeout,\n )\n self.tools.append(mcp_tool)\n\n conn_info = self.url if self.url else self.command\n print(f\"✓ Connected to MCP server '{self.name}' ({self.connection_type}: {conn_info}) - loaded {len(self.tools)} tools\")\n for tool in self.tools:\n desc = tool.description[:60] if len(tool.description) > 60 else tool.description\n print(f\" - {tool.name}: {desc}...\")\n return True\n\n except TimeoutError:\n print(f\"✗ Connection to MCP server '{self.name}' timed out after {connect_timeout}s\")\n if self.exit_stack:\n await self.exit_stack.aclose()\n self.exit_stack = None\n return False\n\n except Exception as e:\n print(f\"✗ Failed to connect to MCP server '{self.name}': {e}\")\n if self.exit_stack:\n await self.exit_stack.aclose()\n self.exit_stack = None\n import traceback\n\n traceback.print_exc()\n return False\n\n async def _connect_stdio(self):\n \"\"\"Connect via STDIO transport.\"\"\"\n server_params = StdioServerParameters(command=self.command, args=self.args, env=self.env if self.env else None)\n return await self.exit_stack.enter_async_context(stdio_client(server_params))\n\n async def _connect_sse(self):\n \"\"\"Connect via SSE transport with timeout parameters.\"\"\"\n connect_timeout = self._get_connect_timeout()\n sse_read_timeout = self._get_sse_read_timeout()\n\n return await self.exit_stack.enter_async_context(\n sse_client(\n url=self.url,\n headers=self.headers if self.headers else None,\n timeout=connect_timeout,\n sse_read_timeout=sse_read_timeout,\n )\n )\n\n async def _connect_streamable_http(self):\n \"\"\"Connect via Streamable HTTP transport with timeout parameters.\"\"\"\n connect_timeout = self._get_connect_timeout()\n sse_read_timeout = self._get_sse_read_timeout()\n\n # streamablehttp_client returns (read, write, get_session_id)\n read_stream, write_stream, _ = await self.exit_stack.enter_async_context(\n streamablehttp_client(\n url=self.url,\n headers=self.headers if self.headers else None,\n timeout=connect_timeout,\n sse_read_timeout=sse_read_timeout,\n )\n )\n return read_stream, write_stream\n\n async def disconnect(self):\n \"\"\"Properly disconnect from the MCP server.\"\"\"\n if self.exit_stack:\n try:\n await self.exit_stack.aclose()\n except Exception:\n # anyio cancel scope may raise RuntimeError or ExceptionGroup\n # when stdio_client's task group is closed from a different\n # task context during shutdown.\n pass\n finally:\n self.exit_stack = None\n self.session = None", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 6464}, "tests/test_mcp.py::166": {"resolved_imports": ["mini_agent/tools/mcp_loader.py"], "used_names": ["MCPTimeoutConfig"], "enclosing_function": "test_default_timeout_config", "extracted_code": "# Source: mini_agent/tools/mcp_loader.py\nclass MCPTimeoutConfig:\n \"\"\"MCP timeout configuration.\"\"\"\n\n connect_timeout: float = 10.0 # Connection timeout (seconds)\n execute_timeout: float = 60.0 # Tool execution timeout (seconds)\n sse_read_timeout: float = 120.0", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 274}, "tests/test_mcp.py::167": {"resolved_imports": ["mini_agent/tools/mcp_loader.py"], "used_names": ["MCPTimeoutConfig"], "enclosing_function": "test_default_timeout_config", "extracted_code": "# Source: mini_agent/tools/mcp_loader.py\nclass MCPTimeoutConfig:\n \"\"\"MCP timeout configuration.\"\"\"\n\n connect_timeout: float = 10.0 # Connection timeout (seconds)\n execute_timeout: float = 60.0 # Tool execution timeout (seconds)\n sse_read_timeout: float = 120.0", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 274}, "tests/test_mcp.py::178": {"resolved_imports": ["mini_agent/tools/mcp_loader.py"], "used_names": ["MCPTimeoutConfig"], "enclosing_function": "test_custom_timeout_config", "extracted_code": "# Source: mini_agent/tools/mcp_loader.py\nclass MCPTimeoutConfig:\n \"\"\"MCP timeout configuration.\"\"\"\n\n connect_timeout: float = 10.0 # Connection timeout (seconds)\n execute_timeout: float = 60.0 # Tool execution timeout (seconds)\n sse_read_timeout: float = 120.0", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 274}, "tests/test_mcp.py::233": {"resolved_imports": ["mini_agent/tools/mcp_loader.py"], "used_names": ["MCPServerConnection"], "enclosing_function": "test_get_effective_connect_timeout_with_override", "extracted_code": "# Source: mini_agent/tools/mcp_loader.py\nclass MCPServerConnection:\n \"\"\"Manages connection to a single MCP server (STDIO or URL-based) with timeout handling.\"\"\"\n\n def __init__(\n self,\n name: str,\n connection_type: ConnectionType = \"stdio\",\n # STDIO params\n command: str | None = None,\n args: list[str] | None = None,\n env: dict[str, str] | None = None,\n # URL-based params\n url: str | None = None,\n headers: dict[str, str] | None = None,\n # Timeout overrides (per-server)\n connect_timeout: float | None = None,\n execute_timeout: float | None = None,\n sse_read_timeout: float | None = None,\n ):\n self.name = name\n self.connection_type = connection_type\n # STDIO\n self.command = command\n self.args = args or []\n self.env = env or {}\n # URL-based\n self.url = url\n self.headers = headers or {}\n # Timeout settings (per-server overrides)\n self.connect_timeout = connect_timeout\n self.execute_timeout = execute_timeout\n self.sse_read_timeout = sse_read_timeout\n # Connection state\n self.session: ClientSession | None = None\n self.exit_stack: AsyncExitStack | None = None\n self.tools: list[MCPTool] = []\n\n def _get_connect_timeout(self) -> float:\n \"\"\"Get effective connect timeout.\"\"\"\n return self.connect_timeout or _default_timeout_config.connect_timeout\n\n def _get_sse_read_timeout(self) -> float:\n \"\"\"Get effective SSE read timeout.\"\"\"\n return self.sse_read_timeout or _default_timeout_config.sse_read_timeout\n\n def _get_execute_timeout(self) -> float:\n \"\"\"Get effective execute timeout.\"\"\"\n return self.execute_timeout or _default_timeout_config.execute_timeout\n\n async def connect(self) -> bool:\n \"\"\"Connect to the MCP server with timeout protection.\"\"\"\n connect_timeout = self._get_connect_timeout()\n\n try:\n self.exit_stack = AsyncExitStack()\n\n # Wrap connection with timeout\n async with asyncio.timeout(connect_timeout):\n if self.connection_type == \"stdio\":\n read_stream, write_stream = await self._connect_stdio()\n elif self.connection_type == \"sse\":\n read_stream, write_stream = await self._connect_sse()\n else: # http / streamable_http\n read_stream, write_stream = await self._connect_streamable_http()\n\n # Enter client session context\n session = await self.exit_stack.enter_async_context(ClientSession(read_stream, write_stream))\n self.session = session\n\n # Initialize the session\n await session.initialize()\n\n # List available tools\n tools_list = await session.list_tools()\n\n # Wrap each tool with execute timeout\n execute_timeout = self._get_execute_timeout()\n for tool in tools_list.tools:\n parameters = tool.inputSchema if hasattr(tool, \"inputSchema\") else {}\n mcp_tool = MCPTool(\n name=tool.name,\n description=tool.description or \"\",\n parameters=parameters,\n session=session,\n execute_timeout=execute_timeout,\n )\n self.tools.append(mcp_tool)\n\n conn_info = self.url if self.url else self.command\n print(f\"✓ Connected to MCP server '{self.name}' ({self.connection_type}: {conn_info}) - loaded {len(self.tools)} tools\")\n for tool in self.tools:\n desc = tool.description[:60] if len(tool.description) > 60 else tool.description\n print(f\" - {tool.name}: {desc}...\")\n return True\n\n except TimeoutError:\n print(f\"✗ Connection to MCP server '{self.name}' timed out after {connect_timeout}s\")\n if self.exit_stack:\n await self.exit_stack.aclose()\n self.exit_stack = None\n return False\n\n except Exception as e:\n print(f\"✗ Failed to connect to MCP server '{self.name}': {e}\")\n if self.exit_stack:\n await self.exit_stack.aclose()\n self.exit_stack = None\n import traceback\n\n traceback.print_exc()\n return False\n\n async def _connect_stdio(self):\n \"\"\"Connect via STDIO transport.\"\"\"\n server_params = StdioServerParameters(command=self.command, args=self.args, env=self.env if self.env else None)\n return await self.exit_stack.enter_async_context(stdio_client(server_params))\n\n async def _connect_sse(self):\n \"\"\"Connect via SSE transport with timeout parameters.\"\"\"\n connect_timeout = self._get_connect_timeout()\n sse_read_timeout = self._get_sse_read_timeout()\n\n return await self.exit_stack.enter_async_context(\n sse_client(\n url=self.url,\n headers=self.headers if self.headers else None,\n timeout=connect_timeout,\n sse_read_timeout=sse_read_timeout,\n )\n )\n\n async def _connect_streamable_http(self):\n \"\"\"Connect via Streamable HTTP transport with timeout parameters.\"\"\"\n connect_timeout = self._get_connect_timeout()\n sse_read_timeout = self._get_sse_read_timeout()\n\n # streamablehttp_client returns (read, write, get_session_id)\n read_stream, write_stream, _ = await self.exit_stack.enter_async_context(\n streamablehttp_client(\n url=self.url,\n headers=self.headers if self.headers else None,\n timeout=connect_timeout,\n sse_read_timeout=sse_read_timeout,\n )\n )\n return read_stream, write_stream\n\n async def disconnect(self):\n \"\"\"Properly disconnect from the MCP server.\"\"\"\n if self.exit_stack:\n try:\n await self.exit_stack.aclose()\n except Exception:\n # anyio cancel scope may raise RuntimeError or ExceptionGroup\n # when stdio_client's task group is closed from a different\n # task context during shutdown.\n pass\n finally:\n self.exit_stack = None\n self.session = None", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 6464}, "tests/test_note_tool.py::43": {"resolved_imports": ["mini_agent/tools/note_tool.py"], "used_names": ["Path", "RecallNoteTool", "SessionNoteTool", "pytest", "tempfile"], "enclosing_function": "test_record_and_recall_notes", "extracted_code": "# Source: mini_agent/tools/note_tool.py\nclass SessionNoteTool(Tool):\n \"\"\"Tool for recording and recalling session notes.\n\n The agent can use this tool to:\n - Record important facts, decisions, or context during sessions\n - Recall information from previous sessions\n - Build up knowledge over time\n\n Example usage by agent:\n - record_note(\"User prefers concise responses\")\n - record_note(\"Project uses Python 3.12 and async/await\")\n - recall_notes() -> retrieves all recorded notes\n \"\"\"\n\n def __init__(self, memory_file: str = \"./workspace/.agent_memory.json\"):\n \"\"\"Initialize session note tool.\n\n Args:\n memory_file: Path to the note storage file\n \"\"\"\n self.memory_file = Path(memory_file)\n # Lazy loading: file and directory are only created when first note is recorded\n\n @property\n def name(self) -> str:\n return \"record_note\"\n\n @property\n def description(self) -> str:\n return (\n \"Record important information as session notes for future reference. \"\n \"Use this to record key facts, user preferences, decisions, or context \"\n \"that should be recalled later in the agent execution chain. Each note is timestamped.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"content\": {\n \"type\": \"string\",\n \"description\": \"The information to record as a note. Be concise but specific.\",\n },\n \"category\": {\n \"type\": \"string\",\n \"description\": \"Optional category/tag for this note (e.g., 'user_preference', 'project_info', 'decision')\",\n },\n },\n \"required\": [\"content\"],\n }\n\n def _load_from_file(self) -> list:\n \"\"\"Load notes from file.\n \n Returns empty list if file doesn't exist (lazy loading).\n \"\"\"\n if not self.memory_file.exists():\n return []\n \n try:\n return json.loads(self.memory_file.read_text())\n except Exception:\n return []\n\n def _save_to_file(self, notes: list):\n \"\"\"Save notes to file.\n \n Creates parent directory and file if they don't exist (lazy initialization).\n \"\"\"\n # Ensure parent directory exists when actually saving\n self.memory_file.parent.mkdir(parents=True, exist_ok=True)\n self.memory_file.write_text(json.dumps(notes, indent=2, ensure_ascii=False))\n\n async def execute(self, content: str, category: str = \"general\") -> ToolResult:\n \"\"\"Record a session note.\n\n Args:\n content: The information to record\n category: Category/tag for this note\n\n Returns:\n ToolResult with success status\n \"\"\"\n try:\n # Load existing notes\n notes = self._load_from_file()\n\n # Add new note with timestamp\n note = {\n \"timestamp\": datetime.now().isoformat(),\n \"category\": category,\n \"content\": content,\n }\n notes.append(note)\n\n # Save back to file\n self._save_to_file(notes)\n\n return ToolResult(\n success=True,\n content=f\"Recorded note: {content} (category: {category})\",\n )\n except Exception as e:\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"Failed to record note: {str(e)}\",\n )\n\nclass RecallNoteTool(Tool):\n \"\"\"Tool for recalling recorded session notes.\"\"\"\n\n def __init__(self, memory_file: str = \"./workspace/.agent_memory.json\"):\n \"\"\"Initialize recall note tool.\n\n Args:\n memory_file: Path to the note storage file\n \"\"\"\n self.memory_file = Path(memory_file)\n\n @property\n def name(self) -> str:\n return \"recall_notes\"\n\n @property\n def description(self) -> str:\n return (\n \"Recall all previously recorded session notes. \"\n \"Use this to retrieve important information, context, or decisions \"\n \"from earlier in the session or previous agent execution chains.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"category\": {\n \"type\": \"string\",\n \"description\": \"Optional: filter notes by category\",\n },\n },\n }\n\n async def execute(self, category: str = None) -> ToolResult:\n \"\"\"Recall session notes.\n\n Args:\n category: Optional category filter\n\n Returns:\n ToolResult with notes content\n \"\"\"\n try:\n if not self.memory_file.exists():\n return ToolResult(\n success=True,\n content=\"No notes recorded yet.\",\n )\n\n notes = json.loads(self.memory_file.read_text())\n\n if not notes:\n return ToolResult(\n success=True,\n content=\"No notes recorded yet.\",\n )\n\n # Filter by category if specified\n if category:\n notes = [n for n in notes if n.get(\"category\") == category]\n if not notes:\n return ToolResult(\n success=True,\n content=f\"No notes found in category: {category}\",\n )\n\n # Format notes for display\n formatted = []\n for idx, note in enumerate(notes, 1):\n timestamp = note.get(\"timestamp\", \"unknown time\")\n cat = note.get(\"category\", \"general\")\n content = note.get(\"content\", \"\")\n formatted.append(f\"{idx}. [{cat}] {content}\\n (recorded at {timestamp})\")\n\n result = \"Recorded Notes:\\n\" + \"\\n\".join(formatted)\n\n return ToolResult(success=True, content=result)\n\n except Exception as e:\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"Failed to recall notes: {str(e)}\",\n )", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 6386}, "tests/test_session_integration.py::52": {"resolved_imports": ["mini_agent/llm/__init__.py", "mini_agent/agent.py", "mini_agent/schema/schema.py", "mini_agent/tools/bash_tool.py", "mini_agent/tools/file_tools.py", "mini_agent/tools/note_tool.py"], "used_names": ["Agent", "ReadTool", "SessionNoteTool", "WriteTool"], "enclosing_function": "test_multi_turn_conversation", "extracted_code": "# Source: mini_agent/agent.py\nclass Agent:\n \"\"\"Single agent with basic tools and MCP support.\"\"\"\n\n def __init__(\n self,\n llm_client: LLMClient,\n system_prompt: str,\n tools: list[Tool],\n max_steps: int = 50,\n workspace_dir: str = \"./workspace\",\n token_limit: int = 80000, # Summary triggered when tokens exceed this value\n ):\n self.llm = llm_client\n self.tools = {tool.name: tool for tool in tools}\n self.max_steps = max_steps\n self.token_limit = token_limit\n self.workspace_dir = Path(workspace_dir)\n # Cancellation event for interrupting agent execution (set externally, e.g., by Esc key)\n self.cancel_event: Optional[asyncio.Event] = None\n\n # Ensure workspace exists\n self.workspace_dir.mkdir(parents=True, exist_ok=True)\n\n # Inject workspace information into system prompt if not already present\n if \"Current Workspace\" not in system_prompt:\n workspace_info = f\"\\n\\n## Current Workspace\\nYou are currently working in: `{self.workspace_dir.absolute()}`\\nAll relative paths will be resolved relative to this directory.\"\n system_prompt = system_prompt + workspace_info\n\n self.system_prompt = system_prompt\n\n # Initialize message history\n self.messages: list[Message] = [Message(role=\"system\", content=system_prompt)]\n\n # Initialize logger\n self.logger = AgentLogger()\n\n # Token usage from last API response (updated after each LLM call)\n self.api_total_tokens: int = 0\n # Flag to skip token check right after summary (avoid consecutive triggers)\n self._skip_next_token_check: bool = False\n\n def add_user_message(self, content: str):\n \"\"\"Add a user message to history.\"\"\"\n self.messages.append(Message(role=\"user\", content=content))\n\n def _check_cancelled(self) -> bool:\n \"\"\"Check if agent execution has been cancelled.\n\n Returns:\n True if cancelled, False otherwise.\n \"\"\"\n if self.cancel_event is not None and self.cancel_event.is_set():\n return True\n return False\n\n def _cleanup_incomplete_messages(self):\n \"\"\"Remove the incomplete assistant message and its partial tool results.\n\n This ensures message consistency after cancellation by removing\n only the current step's incomplete messages, preserving completed steps.\n \"\"\"\n # Find the index of the last assistant message\n last_assistant_idx = -1\n for i in range(len(self.messages) - 1, -1, -1):\n if self.messages[i].role == \"assistant\":\n last_assistant_idx = i\n break\n\n if last_assistant_idx == -1:\n # No assistant message found, nothing to clean\n return\n\n # Remove the last assistant message and all tool results after it\n removed_count = len(self.messages) - last_assistant_idx\n if removed_count > 0:\n self.messages = self.messages[:last_assistant_idx]\n print(f\"{Colors.DIM} Cleaned up {removed_count} incomplete message(s){Colors.RESET}\")\n\n def _estimate_tokens(self) -> int:\n \"\"\"Accurately calculate token count for message history using tiktoken\n\n Uses cl100k_base encoder (GPT-4/Claude/M2 compatible)\n \"\"\"\n try:\n # Use cl100k_base encoder (used by GPT-4 and most modern models)\n encoding = tiktoken.get_encoding(\"cl100k_base\")\n except Exception:\n # Fallback: if tiktoken initialization fails, use simple estimation\n return self._estimate_tokens_fallback()\n\n total_tokens = 0\n\n for msg in self.messages:\n # Count text content\n if isinstance(msg.content, str):\n total_tokens += len(encoding.encode(msg.content))\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n # Convert dict to string for calculation\n total_tokens += len(encoding.encode(str(block)))\n\n # Count thinking\n if msg.thinking:\n total_tokens += len(encoding.encode(msg.thinking))\n\n # Count tool_calls\n if msg.tool_calls:\n total_tokens += len(encoding.encode(str(msg.tool_calls)))\n\n # Metadata overhead per message (approximately 4 tokens)\n total_tokens += 4\n\n return total_tokens\n\n def _estimate_tokens_fallback(self) -> int:\n \"\"\"Fallback token estimation method (when tiktoken is unavailable)\"\"\"\n total_chars = 0\n for msg in self.messages:\n if isinstance(msg.content, str):\n total_chars += len(msg.content)\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n total_chars += len(str(block))\n\n if msg.thinking:\n total_chars += len(msg.thinking)\n\n if msg.tool_calls:\n total_chars += len(str(msg.tool_calls))\n\n # Rough estimation: average 2.5 characters = 1 token\n return int(total_chars / 2.5)\n\n async def _summarize_messages(self):\n \"\"\"Message history summarization: summarize conversations between user messages when tokens exceed limit\n\n Strategy (Agent mode):\n - Keep all user messages (these are user intents)\n - Summarize content between each user-user pair (agent execution process)\n - If last round is still executing (has agent/tool messages but no next user), also summarize\n - Structure: system -> user1 -> summary1 -> user2 -> summary2 -> user3 -> summary3 (if executing)\n\n Summary is triggered when EITHER:\n - Local token estimation exceeds limit\n - API reported total_tokens exceeds limit\n \"\"\"\n # Skip check if we just completed a summary (wait for next LLM call to update api_total_tokens)\n if self._skip_next_token_check:\n self._skip_next_token_check = False\n return\n\n estimated_tokens = self._estimate_tokens()\n\n # Check both local estimation and API reported tokens\n should_summarize = estimated_tokens > self.token_limit or self.api_total_tokens > self.token_limit\n\n # If neither exceeded, no summary needed\n if not should_summarize:\n return\n\n print(\n f\"\\n{Colors.BRIGHT_YELLOW}📊 Token usage - Local estimate: {estimated_tokens}, API reported: {self.api_total_tokens}, Limit: {self.token_limit}{Colors.RESET}\"\n )\n print(f\"{Colors.BRIGHT_YELLOW}🔄 Triggering message history summarization...{Colors.RESET}\")\n\n # Find all user message indices (skip system prompt)\n user_indices = [i for i, msg in enumerate(self.messages) if msg.role == \"user\" and i > 0]\n\n # Need at least 1 user message to perform summary\n if len(user_indices) < 1:\n print(f\"{Colors.BRIGHT_YELLOW}⚠️ Insufficient messages, cannot summarize{Colors.RESET}\")\n return\n\n # Build new message list\n new_messages = [self.messages[0]] # Keep system prompt\n summary_count = 0\n\n # Iterate through each user message and summarize the execution process after it\n for i, user_idx in enumerate(user_indices):\n # Add current user message\n new_messages.append(self.messages[user_idx])\n\n # Determine message range to summarize\n # If last user, go to end of message list; otherwise to before next user\n if i < len(user_indices) - 1:\n next_user_idx = user_indices[i + 1]\n else:\n next_user_idx = len(self.messages)\n\n # Extract execution messages for this round\n execution_messages = self.messages[user_idx + 1 : next_user_idx]\n\n # If there are execution messages in this round, summarize them\n if execution_messages:\n summary_text = await self._create_summary(execution_messages, i + 1)\n if summary_text:\n summary_message = Message(\n role=\"user\",\n content=f\"[Assistant Execution Summary]\\n\\n{summary_text}\",\n )\n new_messages.append(summary_message)\n summary_count += 1\n\n # Replace message list\n self.messages = new_messages\n\n # Skip next token check to avoid consecutive summary triggers\n # (api_total_tokens will be updated after next LLM call)\n self._skip_next_token_check = True\n\n new_tokens = self._estimate_tokens()\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary completed, local tokens: {estimated_tokens} → {new_tokens}{Colors.RESET}\")\n print(f\"{Colors.DIM} Structure: system + {len(user_indices)} user messages + {summary_count} summaries{Colors.RESET}\")\n print(f\"{Colors.DIM} Note: API token count will update on next LLM call{Colors.RESET}\")\n\n async def _create_summary(self, messages: list[Message], round_num: int) -> str:\n \"\"\"Create summary for one execution round\n\n Args:\n messages: List of messages to summarize\n round_num: Round number\n\n Returns:\n Summary text\n \"\"\"\n if not messages:\n return \"\"\n\n # Build summary content\n summary_content = f\"Round {round_num} execution process:\\n\\n\"\n for msg in messages:\n if msg.role == \"assistant\":\n content_text = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\"Assistant: {content_text}\\n\"\n if msg.tool_calls:\n tool_names = [tc.function.name for tc in msg.tool_calls]\n summary_content += f\" → Called tools: {', '.join(tool_names)}\\n\"\n elif msg.role == \"tool\":\n result_preview = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\" ← Tool returned: {result_preview}...\\n\"\n\n # Call LLM to generate concise summary\n try:\n summary_prompt = f\"\"\"Please provide a concise summary of the following Agent execution process:\n\n{summary_content}\n\nRequirements:\n1. Focus on what tasks were completed and which tools were called\n2. Keep key execution results and important findings\n3. Be concise and clear, within 1000 words\n4. Use English\n5. Do not include \"user\" related content, only summarize the Agent's execution process\"\"\"\n\n summary_msg = Message(role=\"user\", content=summary_prompt)\n response = await self.llm.generate(\n messages=[\n Message(\n role=\"system\",\n content=\"You are an assistant skilled at summarizing Agent execution processes.\",\n ),\n summary_msg,\n ]\n )\n\n summary_text = response.content\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary for round {round_num} generated successfully{Colors.RESET}\")\n return summary_text\n\n except Exception as e:\n print(f\"{Colors.BRIGHT_RED}✗ Summary generation failed for round {round_num}: {e}{Colors.RESET}\")\n # Use simple text summary on failure\n return summary_content\n\n async def run(self, cancel_event: Optional[asyncio.Event] = None) -> str:\n \"\"\"Execute agent loop until task is complete or max steps reached.\n\n Args:\n cancel_event: Optional asyncio.Event that can be set to cancel execution.\n When set, the agent will stop at the next safe checkpoint\n (after completing the current step to keep messages consistent).\n\n Returns:\n The final response content, or error message (including cancellation message).\n \"\"\"\n # Set cancellation event (can also be set via self.cancel_event before calling run())\n if cancel_event is not None:\n self.cancel_event = cancel_event\n\n # Start new run, initialize log file\n self.logger.start_new_run()\n print(f\"{Colors.DIM}📝 Log file: {self.logger.get_log_file_path()}{Colors.RESET}\")\n\n step = 0\n run_start_time = perf_counter()\n\n while step < self.max_steps:\n # Check for cancellation at start of each step\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_start_time = perf_counter()\n # Check and summarize message history to prevent context overflow\n await self._summarize_messages()\n\n # Step header with proper width calculation\n BOX_WIDTH = 58\n step_text = f\"{Colors.BOLD}{Colors.BRIGHT_CYAN}💭 Step {step + 1}/{self.max_steps}{Colors.RESET}\"\n step_display_width = calculate_display_width(step_text)\n padding = max(0, BOX_WIDTH - 1 - step_display_width) # -1 for leading space\n\n print(f\"\\n{Colors.DIM}╭{'─' * BOX_WIDTH}╮{Colors.RESET}\")\n print(f\"{Colors.DIM}│{Colors.RESET} {step_text}{' ' * padding}{Colors.DIM}│{Colors.RESET}\")\n print(f\"{Colors.DIM}╰{'─' * BOX_WIDTH}╯{Colors.RESET}\")\n\n # Get tool list for LLM call\n tool_list = list(self.tools.values())\n\n # Log LLM request and call LLM with Tool objects directly\n self.logger.log_request(messages=self.messages, tools=tool_list)\n\n try:\n response = await self.llm.generate(messages=self.messages, tools=tool_list)\n except Exception as e:\n # Check if it's a retry exhausted error\n from .retry import RetryExhaustedError\n\n if isinstance(e, RetryExhaustedError):\n error_msg = f\"LLM call failed after {e.attempts} retries\\nLast error: {str(e.last_exception)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Retry failed:{Colors.RESET} {error_msg}\")\n else:\n error_msg = f\"LLM call failed: {str(e)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Error:{Colors.RESET} {error_msg}\")\n return error_msg\n\n # Accumulate API reported token usage\n if response.usage:\n self.api_total_tokens = response.usage.total_tokens\n\n # Log LLM response\n self.logger.log_response(\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n finish_reason=response.finish_reason,\n )\n\n # Add assistant message\n assistant_msg = Message(\n role=\"assistant\",\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n )\n self.messages.append(assistant_msg)\n\n # Print thinking if present\n if response.thinking:\n print(f\"\\n{Colors.BOLD}{Colors.MAGENTA}🧠 Thinking:{Colors.RESET}\")\n print(f\"{Colors.DIM}{response.thinking}{Colors.RESET}\")\n\n # Print assistant response\n if response.content:\n print(f\"\\n{Colors.BOLD}{Colors.BRIGHT_BLUE}🤖 Assistant:{Colors.RESET}\")\n print(f\"{response.content}\")\n\n # Check if task is complete (no tool calls)\n if not response.tool_calls:\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n return response.content\n\n # Check for cancellation before executing tools\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n # Execute tool calls\n for tool_call in response.tool_calls:\n tool_call_id = tool_call.id\n function_name = tool_call.function.name\n arguments = tool_call.function.arguments\n\n # Tool call header\n print(f\"\\n{Colors.BRIGHT_YELLOW}🔧 Tool Call:{Colors.RESET} {Colors.BOLD}{Colors.CYAN}{function_name}{Colors.RESET}\")\n\n # Arguments (formatted display)\n print(f\"{Colors.DIM} Arguments:{Colors.RESET}\")\n # Truncate each argument value to avoid overly long output\n truncated_args = {}\n for key, value in arguments.items():\n value_str = str(value)\n if len(value_str) > 200:\n truncated_args[key] = value_str[:200] + \"...\"\n else:\n truncated_args[key] = value\n args_json = json.dumps(truncated_args, indent=2, ensure_ascii=False)\n for line in args_json.split(\"\\n\"):\n print(f\" {Colors.DIM}{line}{Colors.RESET}\")\n\n # Execute tool\n if function_name not in self.tools:\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Unknown tool: {function_name}\",\n )\n else:\n try:\n tool = self.tools[function_name]\n result = await tool.execute(**arguments)\n except Exception as e:\n # Catch all exceptions during tool execution, convert to failed ToolResult\n import traceback\n\n error_detail = f\"{type(e).__name__}: {str(e)}\"\n error_trace = traceback.format_exc()\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Tool execution failed: {error_detail}\\n\\nTraceback:\\n{error_trace}\",\n )\n\n # Log tool execution result\n self.logger.log_tool_result(\n tool_name=function_name,\n arguments=arguments,\n result_success=result.success,\n result_content=result.content if result.success else None,\n result_error=result.error if not result.success else None,\n )\n\n # Print result\n if result.success:\n result_text = result.content\n if len(result_text) > 300:\n result_text = result_text[:300] + f\"{Colors.DIM}...{Colors.RESET}\"\n print(f\"{Colors.BRIGHT_GREEN}✓ Result:{Colors.RESET} {result_text}\")\n else:\n print(f\"{Colors.BRIGHT_RED}✗ Error:{Colors.RESET} {Colors.RED}{result.error}{Colors.RESET}\")\n\n # Add tool result message\n tool_msg = Message(\n role=\"tool\",\n content=result.content if result.success else f\"Error: {result.error}\",\n tool_call_id=tool_call_id,\n name=function_name,\n )\n self.messages.append(tool_msg)\n\n # Check for cancellation after each tool execution\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n\n step += 1\n\n # Max steps reached\n error_msg = f\"Task couldn't be completed after {self.max_steps} steps.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {error_msg}{Colors.RESET}\")\n return error_msg\n\n def get_history(self) -> list[Message]:\n \"\"\"Get message history.\"\"\"\n return self.messages.copy()\n\n\n# Source: mini_agent/tools/file_tools.py\nclass ReadTool(Tool):\n \"\"\"Read file content.\"\"\"\n\n def __init__(self, workspace_dir: str = \".\"):\n \"\"\"Initialize ReadTool with workspace directory.\n\n Args:\n workspace_dir: Base directory for resolving relative paths\n \"\"\"\n self.workspace_dir = Path(workspace_dir).absolute()\n\n @property\n def name(self) -> str:\n return \"read_file\"\n\n @property\n def description(self) -> str:\n return (\n \"Read file contents from the filesystem. Output always includes line numbers \"\n \"in format 'LINE_NUMBER|LINE_CONTENT' (1-indexed). Supports reading partial content \"\n \"by specifying line offset and limit for large files. \"\n \"You can call this tool multiple times in parallel to read different files simultaneously.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"type\": \"string\",\n \"description\": \"Absolute or relative path to the file\",\n },\n \"offset\": {\n \"type\": \"integer\",\n \"description\": \"Starting line number (1-indexed). Use for large files to read from specific line\",\n },\n \"limit\": {\n \"type\": \"integer\",\n \"description\": \"Number of lines to read. Use with offset for large files to read in chunks\",\n },\n },\n \"required\": [\"path\"],\n }\n\n async def execute(self, path: str, offset: int | None = None, limit: int | None = None) -> ToolResult:\n \"\"\"Execute read file.\"\"\"\n try:\n file_path = Path(path)\n # Resolve relative paths relative to workspace_dir\n if not file_path.is_absolute():\n file_path = self.workspace_dir / file_path\n\n if not file_path.exists():\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"File not found: {path}\",\n )\n\n # Read file content with line numbers\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.readlines()\n\n # Apply offset and limit\n start = (offset - 1) if offset else 0\n end = (start + limit) if limit else len(lines)\n if start < 0:\n start = 0\n if end > len(lines):\n end = len(lines)\n\n selected_lines = lines[start:end]\n\n # Format with line numbers (1-indexed)\n numbered_lines = []\n for i, line in enumerate(selected_lines, start=start + 1):\n # Remove trailing newline for formatting\n line_content = line.rstrip(\"\\n\")\n numbered_lines.append(f\"{i:6d}|{line_content}\")\n\n content = \"\\n\".join(numbered_lines)\n\n # Apply token truncation if needed\n max_tokens = 32000\n content = truncate_text_by_tokens(content, max_tokens)\n\n return ToolResult(success=True, content=content)\n except Exception as e:\n return ToolResult(success=False, content=\"\", error=str(e))\n\nclass WriteTool(Tool):\n \"\"\"Write content to a file.\"\"\"\n\n def __init__(self, workspace_dir: str = \".\"):\n \"\"\"Initialize WriteTool with workspace directory.\n\n Args:\n workspace_dir: Base directory for resolving relative paths\n \"\"\"\n self.workspace_dir = Path(workspace_dir).absolute()\n\n @property\n def name(self) -> str:\n return \"write_file\"\n\n @property\n def description(self) -> str:\n return (\n \"Write content to a file. Will overwrite existing files completely. \"\n \"For existing files, you should read the file first using read_file. \"\n \"Prefer editing existing files over creating new ones unless explicitly needed.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"type\": \"string\",\n \"description\": \"Absolute or relative path to the file\",\n },\n \"content\": {\n \"type\": \"string\",\n \"description\": \"Complete content to write (will replace existing content)\",\n },\n },\n \"required\": [\"path\", \"content\"],\n }\n\n async def execute(self, path: str, content: str) -> ToolResult:\n \"\"\"Execute write file.\"\"\"\n try:\n file_path = Path(path)\n # Resolve relative paths relative to workspace_dir\n if not file_path.is_absolute():\n file_path = self.workspace_dir / file_path\n\n # Create parent directories if they don't exist\n file_path.parent.mkdir(parents=True, exist_ok=True)\n\n file_path.write_text(content, encoding=\"utf-8\")\n return ToolResult(success=True, content=f\"Successfully wrote to {file_path}\")\n except Exception as e:\n return ToolResult(success=False, content=\"\", error=str(e))\n\n\n# Source: mini_agent/tools/note_tool.py\nclass SessionNoteTool(Tool):\n \"\"\"Tool for recording and recalling session notes.\n\n The agent can use this tool to:\n - Record important facts, decisions, or context during sessions\n - Recall information from previous sessions\n - Build up knowledge over time\n\n Example usage by agent:\n - record_note(\"User prefers concise responses\")\n - record_note(\"Project uses Python 3.12 and async/await\")\n - recall_notes() -> retrieves all recorded notes\n \"\"\"\n\n def __init__(self, memory_file: str = \"./workspace/.agent_memory.json\"):\n \"\"\"Initialize session note tool.\n\n Args:\n memory_file: Path to the note storage file\n \"\"\"\n self.memory_file = Path(memory_file)\n # Lazy loading: file and directory are only created when first note is recorded\n\n @property\n def name(self) -> str:\n return \"record_note\"\n\n @property\n def description(self) -> str:\n return (\n \"Record important information as session notes for future reference. \"\n \"Use this to record key facts, user preferences, decisions, or context \"\n \"that should be recalled later in the agent execution chain. Each note is timestamped.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"content\": {\n \"type\": \"string\",\n \"description\": \"The information to record as a note. Be concise but specific.\",\n },\n \"category\": {\n \"type\": \"string\",\n \"description\": \"Optional category/tag for this note (e.g., 'user_preference', 'project_info', 'decision')\",\n },\n },\n \"required\": [\"content\"],\n }\n\n def _load_from_file(self) -> list:\n \"\"\"Load notes from file.\n \n Returns empty list if file doesn't exist (lazy loading).\n \"\"\"\n if not self.memory_file.exists():\n return []\n \n try:\n return json.loads(self.memory_file.read_text())\n except Exception:\n return []\n\n def _save_to_file(self, notes: list):\n \"\"\"Save notes to file.\n \n Creates parent directory and file if they don't exist (lazy initialization).\n \"\"\"\n # Ensure parent directory exists when actually saving\n self.memory_file.parent.mkdir(parents=True, exist_ok=True)\n self.memory_file.write_text(json.dumps(notes, indent=2, ensure_ascii=False))\n\n async def execute(self, content: str, category: str = \"general\") -> ToolResult:\n \"\"\"Record a session note.\n\n Args:\n content: The information to record\n category: Category/tag for this note\n\n Returns:\n ToolResult with success status\n \"\"\"\n try:\n # Load existing notes\n notes = self._load_from_file()\n\n # Add new note with timestamp\n note = {\n \"timestamp\": datetime.now().isoformat(),\n \"category\": category,\n \"content\": content,\n }\n notes.append(note)\n\n # Save back to file\n self._save_to_file(notes)\n\n return ToolResult(\n success=True,\n content=f\"Recorded note: {content} (category: {category})\",\n )\n except Exception as e:\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"Failed to record note: {str(e)}\",\n )", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 29731}, "tests/test_session_integration.py::60": {"resolved_imports": ["mini_agent/llm/__init__.py", "mini_agent/agent.py", "mini_agent/schema/schema.py", "mini_agent/tools/bash_tool.py", "mini_agent/tools/file_tools.py", "mini_agent/tools/note_tool.py"], "used_names": ["Agent", "ReadTool", "SessionNoteTool", "WriteTool"], "enclosing_function": "test_multi_turn_conversation", "extracted_code": "# Source: mini_agent/agent.py\nclass Agent:\n \"\"\"Single agent with basic tools and MCP support.\"\"\"\n\n def __init__(\n self,\n llm_client: LLMClient,\n system_prompt: str,\n tools: list[Tool],\n max_steps: int = 50,\n workspace_dir: str = \"./workspace\",\n token_limit: int = 80000, # Summary triggered when tokens exceed this value\n ):\n self.llm = llm_client\n self.tools = {tool.name: tool for tool in tools}\n self.max_steps = max_steps\n self.token_limit = token_limit\n self.workspace_dir = Path(workspace_dir)\n # Cancellation event for interrupting agent execution (set externally, e.g., by Esc key)\n self.cancel_event: Optional[asyncio.Event] = None\n\n # Ensure workspace exists\n self.workspace_dir.mkdir(parents=True, exist_ok=True)\n\n # Inject workspace information into system prompt if not already present\n if \"Current Workspace\" not in system_prompt:\n workspace_info = f\"\\n\\n## Current Workspace\\nYou are currently working in: `{self.workspace_dir.absolute()}`\\nAll relative paths will be resolved relative to this directory.\"\n system_prompt = system_prompt + workspace_info\n\n self.system_prompt = system_prompt\n\n # Initialize message history\n self.messages: list[Message] = [Message(role=\"system\", content=system_prompt)]\n\n # Initialize logger\n self.logger = AgentLogger()\n\n # Token usage from last API response (updated after each LLM call)\n self.api_total_tokens: int = 0\n # Flag to skip token check right after summary (avoid consecutive triggers)\n self._skip_next_token_check: bool = False\n\n def add_user_message(self, content: str):\n \"\"\"Add a user message to history.\"\"\"\n self.messages.append(Message(role=\"user\", content=content))\n\n def _check_cancelled(self) -> bool:\n \"\"\"Check if agent execution has been cancelled.\n\n Returns:\n True if cancelled, False otherwise.\n \"\"\"\n if self.cancel_event is not None and self.cancel_event.is_set():\n return True\n return False\n\n def _cleanup_incomplete_messages(self):\n \"\"\"Remove the incomplete assistant message and its partial tool results.\n\n This ensures message consistency after cancellation by removing\n only the current step's incomplete messages, preserving completed steps.\n \"\"\"\n # Find the index of the last assistant message\n last_assistant_idx = -1\n for i in range(len(self.messages) - 1, -1, -1):\n if self.messages[i].role == \"assistant\":\n last_assistant_idx = i\n break\n\n if last_assistant_idx == -1:\n # No assistant message found, nothing to clean\n return\n\n # Remove the last assistant message and all tool results after it\n removed_count = len(self.messages) - last_assistant_idx\n if removed_count > 0:\n self.messages = self.messages[:last_assistant_idx]\n print(f\"{Colors.DIM} Cleaned up {removed_count} incomplete message(s){Colors.RESET}\")\n\n def _estimate_tokens(self) -> int:\n \"\"\"Accurately calculate token count for message history using tiktoken\n\n Uses cl100k_base encoder (GPT-4/Claude/M2 compatible)\n \"\"\"\n try:\n # Use cl100k_base encoder (used by GPT-4 and most modern models)\n encoding = tiktoken.get_encoding(\"cl100k_base\")\n except Exception:\n # Fallback: if tiktoken initialization fails, use simple estimation\n return self._estimate_tokens_fallback()\n\n total_tokens = 0\n\n for msg in self.messages:\n # Count text content\n if isinstance(msg.content, str):\n total_tokens += len(encoding.encode(msg.content))\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n # Convert dict to string for calculation\n total_tokens += len(encoding.encode(str(block)))\n\n # Count thinking\n if msg.thinking:\n total_tokens += len(encoding.encode(msg.thinking))\n\n # Count tool_calls\n if msg.tool_calls:\n total_tokens += len(encoding.encode(str(msg.tool_calls)))\n\n # Metadata overhead per message (approximately 4 tokens)\n total_tokens += 4\n\n return total_tokens\n\n def _estimate_tokens_fallback(self) -> int:\n \"\"\"Fallback token estimation method (when tiktoken is unavailable)\"\"\"\n total_chars = 0\n for msg in self.messages:\n if isinstance(msg.content, str):\n total_chars += len(msg.content)\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n total_chars += len(str(block))\n\n if msg.thinking:\n total_chars += len(msg.thinking)\n\n if msg.tool_calls:\n total_chars += len(str(msg.tool_calls))\n\n # Rough estimation: average 2.5 characters = 1 token\n return int(total_chars / 2.5)\n\n async def _summarize_messages(self):\n \"\"\"Message history summarization: summarize conversations between user messages when tokens exceed limit\n\n Strategy (Agent mode):\n - Keep all user messages (these are user intents)\n - Summarize content between each user-user pair (agent execution process)\n - If last round is still executing (has agent/tool messages but no next user), also summarize\n - Structure: system -> user1 -> summary1 -> user2 -> summary2 -> user3 -> summary3 (if executing)\n\n Summary is triggered when EITHER:\n - Local token estimation exceeds limit\n - API reported total_tokens exceeds limit\n \"\"\"\n # Skip check if we just completed a summary (wait for next LLM call to update api_total_tokens)\n if self._skip_next_token_check:\n self._skip_next_token_check = False\n return\n\n estimated_tokens = self._estimate_tokens()\n\n # Check both local estimation and API reported tokens\n should_summarize = estimated_tokens > self.token_limit or self.api_total_tokens > self.token_limit\n\n # If neither exceeded, no summary needed\n if not should_summarize:\n return\n\n print(\n f\"\\n{Colors.BRIGHT_YELLOW}📊 Token usage - Local estimate: {estimated_tokens}, API reported: {self.api_total_tokens}, Limit: {self.token_limit}{Colors.RESET}\"\n )\n print(f\"{Colors.BRIGHT_YELLOW}🔄 Triggering message history summarization...{Colors.RESET}\")\n\n # Find all user message indices (skip system prompt)\n user_indices = [i for i, msg in enumerate(self.messages) if msg.role == \"user\" and i > 0]\n\n # Need at least 1 user message to perform summary\n if len(user_indices) < 1:\n print(f\"{Colors.BRIGHT_YELLOW}⚠️ Insufficient messages, cannot summarize{Colors.RESET}\")\n return\n\n # Build new message list\n new_messages = [self.messages[0]] # Keep system prompt\n summary_count = 0\n\n # Iterate through each user message and summarize the execution process after it\n for i, user_idx in enumerate(user_indices):\n # Add current user message\n new_messages.append(self.messages[user_idx])\n\n # Determine message range to summarize\n # If last user, go to end of message list; otherwise to before next user\n if i < len(user_indices) - 1:\n next_user_idx = user_indices[i + 1]\n else:\n next_user_idx = len(self.messages)\n\n # Extract execution messages for this round\n execution_messages = self.messages[user_idx + 1 : next_user_idx]\n\n # If there are execution messages in this round, summarize them\n if execution_messages:\n summary_text = await self._create_summary(execution_messages, i + 1)\n if summary_text:\n summary_message = Message(\n role=\"user\",\n content=f\"[Assistant Execution Summary]\\n\\n{summary_text}\",\n )\n new_messages.append(summary_message)\n summary_count += 1\n\n # Replace message list\n self.messages = new_messages\n\n # Skip next token check to avoid consecutive summary triggers\n # (api_total_tokens will be updated after next LLM call)\n self._skip_next_token_check = True\n\n new_tokens = self._estimate_tokens()\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary completed, local tokens: {estimated_tokens} → {new_tokens}{Colors.RESET}\")\n print(f\"{Colors.DIM} Structure: system + {len(user_indices)} user messages + {summary_count} summaries{Colors.RESET}\")\n print(f\"{Colors.DIM} Note: API token count will update on next LLM call{Colors.RESET}\")\n\n async def _create_summary(self, messages: list[Message], round_num: int) -> str:\n \"\"\"Create summary for one execution round\n\n Args:\n messages: List of messages to summarize\n round_num: Round number\n\n Returns:\n Summary text\n \"\"\"\n if not messages:\n return \"\"\n\n # Build summary content\n summary_content = f\"Round {round_num} execution process:\\n\\n\"\n for msg in messages:\n if msg.role == \"assistant\":\n content_text = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\"Assistant: {content_text}\\n\"\n if msg.tool_calls:\n tool_names = [tc.function.name for tc in msg.tool_calls]\n summary_content += f\" → Called tools: {', '.join(tool_names)}\\n\"\n elif msg.role == \"tool\":\n result_preview = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\" ← Tool returned: {result_preview}...\\n\"\n\n # Call LLM to generate concise summary\n try:\n summary_prompt = f\"\"\"Please provide a concise summary of the following Agent execution process:\n\n{summary_content}\n\nRequirements:\n1. Focus on what tasks were completed and which tools were called\n2. Keep key execution results and important findings\n3. Be concise and clear, within 1000 words\n4. Use English\n5. Do not include \"user\" related content, only summarize the Agent's execution process\"\"\"\n\n summary_msg = Message(role=\"user\", content=summary_prompt)\n response = await self.llm.generate(\n messages=[\n Message(\n role=\"system\",\n content=\"You are an assistant skilled at summarizing Agent execution processes.\",\n ),\n summary_msg,\n ]\n )\n\n summary_text = response.content\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary for round {round_num} generated successfully{Colors.RESET}\")\n return summary_text\n\n except Exception as e:\n print(f\"{Colors.BRIGHT_RED}✗ Summary generation failed for round {round_num}: {e}{Colors.RESET}\")\n # Use simple text summary on failure\n return summary_content\n\n async def run(self, cancel_event: Optional[asyncio.Event] = None) -> str:\n \"\"\"Execute agent loop until task is complete or max steps reached.\n\n Args:\n cancel_event: Optional asyncio.Event that can be set to cancel execution.\n When set, the agent will stop at the next safe checkpoint\n (after completing the current step to keep messages consistent).\n\n Returns:\n The final response content, or error message (including cancellation message).\n \"\"\"\n # Set cancellation event (can also be set via self.cancel_event before calling run())\n if cancel_event is not None:\n self.cancel_event = cancel_event\n\n # Start new run, initialize log file\n self.logger.start_new_run()\n print(f\"{Colors.DIM}📝 Log file: {self.logger.get_log_file_path()}{Colors.RESET}\")\n\n step = 0\n run_start_time = perf_counter()\n\n while step < self.max_steps:\n # Check for cancellation at start of each step\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_start_time = perf_counter()\n # Check and summarize message history to prevent context overflow\n await self._summarize_messages()\n\n # Step header with proper width calculation\n BOX_WIDTH = 58\n step_text = f\"{Colors.BOLD}{Colors.BRIGHT_CYAN}💭 Step {step + 1}/{self.max_steps}{Colors.RESET}\"\n step_display_width = calculate_display_width(step_text)\n padding = max(0, BOX_WIDTH - 1 - step_display_width) # -1 for leading space\n\n print(f\"\\n{Colors.DIM}╭{'─' * BOX_WIDTH}╮{Colors.RESET}\")\n print(f\"{Colors.DIM}│{Colors.RESET} {step_text}{' ' * padding}{Colors.DIM}│{Colors.RESET}\")\n print(f\"{Colors.DIM}╰{'─' * BOX_WIDTH}╯{Colors.RESET}\")\n\n # Get tool list for LLM call\n tool_list = list(self.tools.values())\n\n # Log LLM request and call LLM with Tool objects directly\n self.logger.log_request(messages=self.messages, tools=tool_list)\n\n try:\n response = await self.llm.generate(messages=self.messages, tools=tool_list)\n except Exception as e:\n # Check if it's a retry exhausted error\n from .retry import RetryExhaustedError\n\n if isinstance(e, RetryExhaustedError):\n error_msg = f\"LLM call failed after {e.attempts} retries\\nLast error: {str(e.last_exception)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Retry failed:{Colors.RESET} {error_msg}\")\n else:\n error_msg = f\"LLM call failed: {str(e)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Error:{Colors.RESET} {error_msg}\")\n return error_msg\n\n # Accumulate API reported token usage\n if response.usage:\n self.api_total_tokens = response.usage.total_tokens\n\n # Log LLM response\n self.logger.log_response(\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n finish_reason=response.finish_reason,\n )\n\n # Add assistant message\n assistant_msg = Message(\n role=\"assistant\",\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n )\n self.messages.append(assistant_msg)\n\n # Print thinking if present\n if response.thinking:\n print(f\"\\n{Colors.BOLD}{Colors.MAGENTA}🧠 Thinking:{Colors.RESET}\")\n print(f\"{Colors.DIM}{response.thinking}{Colors.RESET}\")\n\n # Print assistant response\n if response.content:\n print(f\"\\n{Colors.BOLD}{Colors.BRIGHT_BLUE}🤖 Assistant:{Colors.RESET}\")\n print(f\"{response.content}\")\n\n # Check if task is complete (no tool calls)\n if not response.tool_calls:\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n return response.content\n\n # Check for cancellation before executing tools\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n # Execute tool calls\n for tool_call in response.tool_calls:\n tool_call_id = tool_call.id\n function_name = tool_call.function.name\n arguments = tool_call.function.arguments\n\n # Tool call header\n print(f\"\\n{Colors.BRIGHT_YELLOW}🔧 Tool Call:{Colors.RESET} {Colors.BOLD}{Colors.CYAN}{function_name}{Colors.RESET}\")\n\n # Arguments (formatted display)\n print(f\"{Colors.DIM} Arguments:{Colors.RESET}\")\n # Truncate each argument value to avoid overly long output\n truncated_args = {}\n for key, value in arguments.items():\n value_str = str(value)\n if len(value_str) > 200:\n truncated_args[key] = value_str[:200] + \"...\"\n else:\n truncated_args[key] = value\n args_json = json.dumps(truncated_args, indent=2, ensure_ascii=False)\n for line in args_json.split(\"\\n\"):\n print(f\" {Colors.DIM}{line}{Colors.RESET}\")\n\n # Execute tool\n if function_name not in self.tools:\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Unknown tool: {function_name}\",\n )\n else:\n try:\n tool = self.tools[function_name]\n result = await tool.execute(**arguments)\n except Exception as e:\n # Catch all exceptions during tool execution, convert to failed ToolResult\n import traceback\n\n error_detail = f\"{type(e).__name__}: {str(e)}\"\n error_trace = traceback.format_exc()\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Tool execution failed: {error_detail}\\n\\nTraceback:\\n{error_trace}\",\n )\n\n # Log tool execution result\n self.logger.log_tool_result(\n tool_name=function_name,\n arguments=arguments,\n result_success=result.success,\n result_content=result.content if result.success else None,\n result_error=result.error if not result.success else None,\n )\n\n # Print result\n if result.success:\n result_text = result.content\n if len(result_text) > 300:\n result_text = result_text[:300] + f\"{Colors.DIM}...{Colors.RESET}\"\n print(f\"{Colors.BRIGHT_GREEN}✓ Result:{Colors.RESET} {result_text}\")\n else:\n print(f\"{Colors.BRIGHT_RED}✗ Error:{Colors.RESET} {Colors.RED}{result.error}{Colors.RESET}\")\n\n # Add tool result message\n tool_msg = Message(\n role=\"tool\",\n content=result.content if result.success else f\"Error: {result.error}\",\n tool_call_id=tool_call_id,\n name=function_name,\n )\n self.messages.append(tool_msg)\n\n # Check for cancellation after each tool execution\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n\n step += 1\n\n # Max steps reached\n error_msg = f\"Task couldn't be completed after {self.max_steps} steps.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {error_msg}{Colors.RESET}\")\n return error_msg\n\n def get_history(self) -> list[Message]:\n \"\"\"Get message history.\"\"\"\n return self.messages.copy()\n\n\n# Source: mini_agent/tools/file_tools.py\nclass ReadTool(Tool):\n \"\"\"Read file content.\"\"\"\n\n def __init__(self, workspace_dir: str = \".\"):\n \"\"\"Initialize ReadTool with workspace directory.\n\n Args:\n workspace_dir: Base directory for resolving relative paths\n \"\"\"\n self.workspace_dir = Path(workspace_dir).absolute()\n\n @property\n def name(self) -> str:\n return \"read_file\"\n\n @property\n def description(self) -> str:\n return (\n \"Read file contents from the filesystem. Output always includes line numbers \"\n \"in format 'LINE_NUMBER|LINE_CONTENT' (1-indexed). Supports reading partial content \"\n \"by specifying line offset and limit for large files. \"\n \"You can call this tool multiple times in parallel to read different files simultaneously.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"type\": \"string\",\n \"description\": \"Absolute or relative path to the file\",\n },\n \"offset\": {\n \"type\": \"integer\",\n \"description\": \"Starting line number (1-indexed). Use for large files to read from specific line\",\n },\n \"limit\": {\n \"type\": \"integer\",\n \"description\": \"Number of lines to read. Use with offset for large files to read in chunks\",\n },\n },\n \"required\": [\"path\"],\n }\n\n async def execute(self, path: str, offset: int | None = None, limit: int | None = None) -> ToolResult:\n \"\"\"Execute read file.\"\"\"\n try:\n file_path = Path(path)\n # Resolve relative paths relative to workspace_dir\n if not file_path.is_absolute():\n file_path = self.workspace_dir / file_path\n\n if not file_path.exists():\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"File not found: {path}\",\n )\n\n # Read file content with line numbers\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.readlines()\n\n # Apply offset and limit\n start = (offset - 1) if offset else 0\n end = (start + limit) if limit else len(lines)\n if start < 0:\n start = 0\n if end > len(lines):\n end = len(lines)\n\n selected_lines = lines[start:end]\n\n # Format with line numbers (1-indexed)\n numbered_lines = []\n for i, line in enumerate(selected_lines, start=start + 1):\n # Remove trailing newline for formatting\n line_content = line.rstrip(\"\\n\")\n numbered_lines.append(f\"{i:6d}|{line_content}\")\n\n content = \"\\n\".join(numbered_lines)\n\n # Apply token truncation if needed\n max_tokens = 32000\n content = truncate_text_by_tokens(content, max_tokens)\n\n return ToolResult(success=True, content=content)\n except Exception as e:\n return ToolResult(success=False, content=\"\", error=str(e))\n\nclass WriteTool(Tool):\n \"\"\"Write content to a file.\"\"\"\n\n def __init__(self, workspace_dir: str = \".\"):\n \"\"\"Initialize WriteTool with workspace directory.\n\n Args:\n workspace_dir: Base directory for resolving relative paths\n \"\"\"\n self.workspace_dir = Path(workspace_dir).absolute()\n\n @property\n def name(self) -> str:\n return \"write_file\"\n\n @property\n def description(self) -> str:\n return (\n \"Write content to a file. Will overwrite existing files completely. \"\n \"For existing files, you should read the file first using read_file. \"\n \"Prefer editing existing files over creating new ones unless explicitly needed.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"type\": \"string\",\n \"description\": \"Absolute or relative path to the file\",\n },\n \"content\": {\n \"type\": \"string\",\n \"description\": \"Complete content to write (will replace existing content)\",\n },\n },\n \"required\": [\"path\", \"content\"],\n }\n\n async def execute(self, path: str, content: str) -> ToolResult:\n \"\"\"Execute write file.\"\"\"\n try:\n file_path = Path(path)\n # Resolve relative paths relative to workspace_dir\n if not file_path.is_absolute():\n file_path = self.workspace_dir / file_path\n\n # Create parent directories if they don't exist\n file_path.parent.mkdir(parents=True, exist_ok=True)\n\n file_path.write_text(content, encoding=\"utf-8\")\n return ToolResult(success=True, content=f\"Successfully wrote to {file_path}\")\n except Exception as e:\n return ToolResult(success=False, content=\"\", error=str(e))\n\n\n# Source: mini_agent/tools/note_tool.py\nclass SessionNoteTool(Tool):\n \"\"\"Tool for recording and recalling session notes.\n\n The agent can use this tool to:\n - Record important facts, decisions, or context during sessions\n - Recall information from previous sessions\n - Build up knowledge over time\n\n Example usage by agent:\n - record_note(\"User prefers concise responses\")\n - record_note(\"Project uses Python 3.12 and async/await\")\n - recall_notes() -> retrieves all recorded notes\n \"\"\"\n\n def __init__(self, memory_file: str = \"./workspace/.agent_memory.json\"):\n \"\"\"Initialize session note tool.\n\n Args:\n memory_file: Path to the note storage file\n \"\"\"\n self.memory_file = Path(memory_file)\n # Lazy loading: file and directory are only created when first note is recorded\n\n @property\n def name(self) -> str:\n return \"record_note\"\n\n @property\n def description(self) -> str:\n return (\n \"Record important information as session notes for future reference. \"\n \"Use this to record key facts, user preferences, decisions, or context \"\n \"that should be recalled later in the agent execution chain. Each note is timestamped.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"content\": {\n \"type\": \"string\",\n \"description\": \"The information to record as a note. Be concise but specific.\",\n },\n \"category\": {\n \"type\": \"string\",\n \"description\": \"Optional category/tag for this note (e.g., 'user_preference', 'project_info', 'decision')\",\n },\n },\n \"required\": [\"content\"],\n }\n\n def _load_from_file(self) -> list:\n \"\"\"Load notes from file.\n \n Returns empty list if file doesn't exist (lazy loading).\n \"\"\"\n if not self.memory_file.exists():\n return []\n \n try:\n return json.loads(self.memory_file.read_text())\n except Exception:\n return []\n\n def _save_to_file(self, notes: list):\n \"\"\"Save notes to file.\n \n Creates parent directory and file if they don't exist (lazy initialization).\n \"\"\"\n # Ensure parent directory exists when actually saving\n self.memory_file.parent.mkdir(parents=True, exist_ok=True)\n self.memory_file.write_text(json.dumps(notes, indent=2, ensure_ascii=False))\n\n async def execute(self, content: str, category: str = \"general\") -> ToolResult:\n \"\"\"Record a session note.\n\n Args:\n content: The information to record\n category: Category/tag for this note\n\n Returns:\n ToolResult with success status\n \"\"\"\n try:\n # Load existing notes\n notes = self._load_from_file()\n\n # Add new note with timestamp\n note = {\n \"timestamp\": datetime.now().isoformat(),\n \"category\": category,\n \"content\": content,\n }\n notes.append(note)\n\n # Save back to file\n self._save_to_file(notes)\n\n return ToolResult(\n success=True,\n content=f\"Recorded note: {content} (category: {category})\",\n )\n except Exception as e:\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"Failed to record note: {str(e)}\",\n )", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 29731}, "tests/test_session_integration.py::66": {"resolved_imports": ["mini_agent/llm/__init__.py", "mini_agent/agent.py", "mini_agent/schema/schema.py", "mini_agent/tools/bash_tool.py", "mini_agent/tools/file_tools.py", "mini_agent/tools/note_tool.py"], "used_names": ["Agent", "ReadTool", "SessionNoteTool", "WriteTool"], "enclosing_function": "test_multi_turn_conversation", "extracted_code": "# Source: mini_agent/agent.py\nclass Agent:\n \"\"\"Single agent with basic tools and MCP support.\"\"\"\n\n def __init__(\n self,\n llm_client: LLMClient,\n system_prompt: str,\n tools: list[Tool],\n max_steps: int = 50,\n workspace_dir: str = \"./workspace\",\n token_limit: int = 80000, # Summary triggered when tokens exceed this value\n ):\n self.llm = llm_client\n self.tools = {tool.name: tool for tool in tools}\n self.max_steps = max_steps\n self.token_limit = token_limit\n self.workspace_dir = Path(workspace_dir)\n # Cancellation event for interrupting agent execution (set externally, e.g., by Esc key)\n self.cancel_event: Optional[asyncio.Event] = None\n\n # Ensure workspace exists\n self.workspace_dir.mkdir(parents=True, exist_ok=True)\n\n # Inject workspace information into system prompt if not already present\n if \"Current Workspace\" not in system_prompt:\n workspace_info = f\"\\n\\n## Current Workspace\\nYou are currently working in: `{self.workspace_dir.absolute()}`\\nAll relative paths will be resolved relative to this directory.\"\n system_prompt = system_prompt + workspace_info\n\n self.system_prompt = system_prompt\n\n # Initialize message history\n self.messages: list[Message] = [Message(role=\"system\", content=system_prompt)]\n\n # Initialize logger\n self.logger = AgentLogger()\n\n # Token usage from last API response (updated after each LLM call)\n self.api_total_tokens: int = 0\n # Flag to skip token check right after summary (avoid consecutive triggers)\n self._skip_next_token_check: bool = False\n\n def add_user_message(self, content: str):\n \"\"\"Add a user message to history.\"\"\"\n self.messages.append(Message(role=\"user\", content=content))\n\n def _check_cancelled(self) -> bool:\n \"\"\"Check if agent execution has been cancelled.\n\n Returns:\n True if cancelled, False otherwise.\n \"\"\"\n if self.cancel_event is not None and self.cancel_event.is_set():\n return True\n return False\n\n def _cleanup_incomplete_messages(self):\n \"\"\"Remove the incomplete assistant message and its partial tool results.\n\n This ensures message consistency after cancellation by removing\n only the current step's incomplete messages, preserving completed steps.\n \"\"\"\n # Find the index of the last assistant message\n last_assistant_idx = -1\n for i in range(len(self.messages) - 1, -1, -1):\n if self.messages[i].role == \"assistant\":\n last_assistant_idx = i\n break\n\n if last_assistant_idx == -1:\n # No assistant message found, nothing to clean\n return\n\n # Remove the last assistant message and all tool results after it\n removed_count = len(self.messages) - last_assistant_idx\n if removed_count > 0:\n self.messages = self.messages[:last_assistant_idx]\n print(f\"{Colors.DIM} Cleaned up {removed_count} incomplete message(s){Colors.RESET}\")\n\n def _estimate_tokens(self) -> int:\n \"\"\"Accurately calculate token count for message history using tiktoken\n\n Uses cl100k_base encoder (GPT-4/Claude/M2 compatible)\n \"\"\"\n try:\n # Use cl100k_base encoder (used by GPT-4 and most modern models)\n encoding = tiktoken.get_encoding(\"cl100k_base\")\n except Exception:\n # Fallback: if tiktoken initialization fails, use simple estimation\n return self._estimate_tokens_fallback()\n\n total_tokens = 0\n\n for msg in self.messages:\n # Count text content\n if isinstance(msg.content, str):\n total_tokens += len(encoding.encode(msg.content))\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n # Convert dict to string for calculation\n total_tokens += len(encoding.encode(str(block)))\n\n # Count thinking\n if msg.thinking:\n total_tokens += len(encoding.encode(msg.thinking))\n\n # Count tool_calls\n if msg.tool_calls:\n total_tokens += len(encoding.encode(str(msg.tool_calls)))\n\n # Metadata overhead per message (approximately 4 tokens)\n total_tokens += 4\n\n return total_tokens\n\n def _estimate_tokens_fallback(self) -> int:\n \"\"\"Fallback token estimation method (when tiktoken is unavailable)\"\"\"\n total_chars = 0\n for msg in self.messages:\n if isinstance(msg.content, str):\n total_chars += len(msg.content)\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n total_chars += len(str(block))\n\n if msg.thinking:\n total_chars += len(msg.thinking)\n\n if msg.tool_calls:\n total_chars += len(str(msg.tool_calls))\n\n # Rough estimation: average 2.5 characters = 1 token\n return int(total_chars / 2.5)\n\n async def _summarize_messages(self):\n \"\"\"Message history summarization: summarize conversations between user messages when tokens exceed limit\n\n Strategy (Agent mode):\n - Keep all user messages (these are user intents)\n - Summarize content between each user-user pair (agent execution process)\n - If last round is still executing (has agent/tool messages but no next user), also summarize\n - Structure: system -> user1 -> summary1 -> user2 -> summary2 -> user3 -> summary3 (if executing)\n\n Summary is triggered when EITHER:\n - Local token estimation exceeds limit\n - API reported total_tokens exceeds limit\n \"\"\"\n # Skip check if we just completed a summary (wait for next LLM call to update api_total_tokens)\n if self._skip_next_token_check:\n self._skip_next_token_check = False\n return\n\n estimated_tokens = self._estimate_tokens()\n\n # Check both local estimation and API reported tokens\n should_summarize = estimated_tokens > self.token_limit or self.api_total_tokens > self.token_limit\n\n # If neither exceeded, no summary needed\n if not should_summarize:\n return\n\n print(\n f\"\\n{Colors.BRIGHT_YELLOW}📊 Token usage - Local estimate: {estimated_tokens}, API reported: {self.api_total_tokens}, Limit: {self.token_limit}{Colors.RESET}\"\n )\n print(f\"{Colors.BRIGHT_YELLOW}🔄 Triggering message history summarization...{Colors.RESET}\")\n\n # Find all user message indices (skip system prompt)\n user_indices = [i for i, msg in enumerate(self.messages) if msg.role == \"user\" and i > 0]\n\n # Need at least 1 user message to perform summary\n if len(user_indices) < 1:\n print(f\"{Colors.BRIGHT_YELLOW}⚠️ Insufficient messages, cannot summarize{Colors.RESET}\")\n return\n\n # Build new message list\n new_messages = [self.messages[0]] # Keep system prompt\n summary_count = 0\n\n # Iterate through each user message and summarize the execution process after it\n for i, user_idx in enumerate(user_indices):\n # Add current user message\n new_messages.append(self.messages[user_idx])\n\n # Determine message range to summarize\n # If last user, go to end of message list; otherwise to before next user\n if i < len(user_indices) - 1:\n next_user_idx = user_indices[i + 1]\n else:\n next_user_idx = len(self.messages)\n\n # Extract execution messages for this round\n execution_messages = self.messages[user_idx + 1 : next_user_idx]\n\n # If there are execution messages in this round, summarize them\n if execution_messages:\n summary_text = await self._create_summary(execution_messages, i + 1)\n if summary_text:\n summary_message = Message(\n role=\"user\",\n content=f\"[Assistant Execution Summary]\\n\\n{summary_text}\",\n )\n new_messages.append(summary_message)\n summary_count += 1\n\n # Replace message list\n self.messages = new_messages\n\n # Skip next token check to avoid consecutive summary triggers\n # (api_total_tokens will be updated after next LLM call)\n self._skip_next_token_check = True\n\n new_tokens = self._estimate_tokens()\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary completed, local tokens: {estimated_tokens} → {new_tokens}{Colors.RESET}\")\n print(f\"{Colors.DIM} Structure: system + {len(user_indices)} user messages + {summary_count} summaries{Colors.RESET}\")\n print(f\"{Colors.DIM} Note: API token count will update on next LLM call{Colors.RESET}\")\n\n async def _create_summary(self, messages: list[Message], round_num: int) -> str:\n \"\"\"Create summary for one execution round\n\n Args:\n messages: List of messages to summarize\n round_num: Round number\n\n Returns:\n Summary text\n \"\"\"\n if not messages:\n return \"\"\n\n # Build summary content\n summary_content = f\"Round {round_num} execution process:\\n\\n\"\n for msg in messages:\n if msg.role == \"assistant\":\n content_text = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\"Assistant: {content_text}\\n\"\n if msg.tool_calls:\n tool_names = [tc.function.name for tc in msg.tool_calls]\n summary_content += f\" → Called tools: {', '.join(tool_names)}\\n\"\n elif msg.role == \"tool\":\n result_preview = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\" ← Tool returned: {result_preview}...\\n\"\n\n # Call LLM to generate concise summary\n try:\n summary_prompt = f\"\"\"Please provide a concise summary of the following Agent execution process:\n\n{summary_content}\n\nRequirements:\n1. Focus on what tasks were completed and which tools were called\n2. Keep key execution results and important findings\n3. Be concise and clear, within 1000 words\n4. Use English\n5. Do not include \"user\" related content, only summarize the Agent's execution process\"\"\"\n\n summary_msg = Message(role=\"user\", content=summary_prompt)\n response = await self.llm.generate(\n messages=[\n Message(\n role=\"system\",\n content=\"You are an assistant skilled at summarizing Agent execution processes.\",\n ),\n summary_msg,\n ]\n )\n\n summary_text = response.content\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary for round {round_num} generated successfully{Colors.RESET}\")\n return summary_text\n\n except Exception as e:\n print(f\"{Colors.BRIGHT_RED}✗ Summary generation failed for round {round_num}: {e}{Colors.RESET}\")\n # Use simple text summary on failure\n return summary_content\n\n async def run(self, cancel_event: Optional[asyncio.Event] = None) -> str:\n \"\"\"Execute agent loop until task is complete or max steps reached.\n\n Args:\n cancel_event: Optional asyncio.Event that can be set to cancel execution.\n When set, the agent will stop at the next safe checkpoint\n (after completing the current step to keep messages consistent).\n\n Returns:\n The final response content, or error message (including cancellation message).\n \"\"\"\n # Set cancellation event (can also be set via self.cancel_event before calling run())\n if cancel_event is not None:\n self.cancel_event = cancel_event\n\n # Start new run, initialize log file\n self.logger.start_new_run()\n print(f\"{Colors.DIM}📝 Log file: {self.logger.get_log_file_path()}{Colors.RESET}\")\n\n step = 0\n run_start_time = perf_counter()\n\n while step < self.max_steps:\n # Check for cancellation at start of each step\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_start_time = perf_counter()\n # Check and summarize message history to prevent context overflow\n await self._summarize_messages()\n\n # Step header with proper width calculation\n BOX_WIDTH = 58\n step_text = f\"{Colors.BOLD}{Colors.BRIGHT_CYAN}💭 Step {step + 1}/{self.max_steps}{Colors.RESET}\"\n step_display_width = calculate_display_width(step_text)\n padding = max(0, BOX_WIDTH - 1 - step_display_width) # -1 for leading space\n\n print(f\"\\n{Colors.DIM}╭{'─' * BOX_WIDTH}╮{Colors.RESET}\")\n print(f\"{Colors.DIM}│{Colors.RESET} {step_text}{' ' * padding}{Colors.DIM}│{Colors.RESET}\")\n print(f\"{Colors.DIM}╰{'─' * BOX_WIDTH}╯{Colors.RESET}\")\n\n # Get tool list for LLM call\n tool_list = list(self.tools.values())\n\n # Log LLM request and call LLM with Tool objects directly\n self.logger.log_request(messages=self.messages, tools=tool_list)\n\n try:\n response = await self.llm.generate(messages=self.messages, tools=tool_list)\n except Exception as e:\n # Check if it's a retry exhausted error\n from .retry import RetryExhaustedError\n\n if isinstance(e, RetryExhaustedError):\n error_msg = f\"LLM call failed after {e.attempts} retries\\nLast error: {str(e.last_exception)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Retry failed:{Colors.RESET} {error_msg}\")\n else:\n error_msg = f\"LLM call failed: {str(e)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Error:{Colors.RESET} {error_msg}\")\n return error_msg\n\n # Accumulate API reported token usage\n if response.usage:\n self.api_total_tokens = response.usage.total_tokens\n\n # Log LLM response\n self.logger.log_response(\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n finish_reason=response.finish_reason,\n )\n\n # Add assistant message\n assistant_msg = Message(\n role=\"assistant\",\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n )\n self.messages.append(assistant_msg)\n\n # Print thinking if present\n if response.thinking:\n print(f\"\\n{Colors.BOLD}{Colors.MAGENTA}🧠 Thinking:{Colors.RESET}\")\n print(f\"{Colors.DIM}{response.thinking}{Colors.RESET}\")\n\n # Print assistant response\n if response.content:\n print(f\"\\n{Colors.BOLD}{Colors.BRIGHT_BLUE}🤖 Assistant:{Colors.RESET}\")\n print(f\"{response.content}\")\n\n # Check if task is complete (no tool calls)\n if not response.tool_calls:\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n return response.content\n\n # Check for cancellation before executing tools\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n # Execute tool calls\n for tool_call in response.tool_calls:\n tool_call_id = tool_call.id\n function_name = tool_call.function.name\n arguments = tool_call.function.arguments\n\n # Tool call header\n print(f\"\\n{Colors.BRIGHT_YELLOW}🔧 Tool Call:{Colors.RESET} {Colors.BOLD}{Colors.CYAN}{function_name}{Colors.RESET}\")\n\n # Arguments (formatted display)\n print(f\"{Colors.DIM} Arguments:{Colors.RESET}\")\n # Truncate each argument value to avoid overly long output\n truncated_args = {}\n for key, value in arguments.items():\n value_str = str(value)\n if len(value_str) > 200:\n truncated_args[key] = value_str[:200] + \"...\"\n else:\n truncated_args[key] = value\n args_json = json.dumps(truncated_args, indent=2, ensure_ascii=False)\n for line in args_json.split(\"\\n\"):\n print(f\" {Colors.DIM}{line}{Colors.RESET}\")\n\n # Execute tool\n if function_name not in self.tools:\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Unknown tool: {function_name}\",\n )\n else:\n try:\n tool = self.tools[function_name]\n result = await tool.execute(**arguments)\n except Exception as e:\n # Catch all exceptions during tool execution, convert to failed ToolResult\n import traceback\n\n error_detail = f\"{type(e).__name__}: {str(e)}\"\n error_trace = traceback.format_exc()\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Tool execution failed: {error_detail}\\n\\nTraceback:\\n{error_trace}\",\n )\n\n # Log tool execution result\n self.logger.log_tool_result(\n tool_name=function_name,\n arguments=arguments,\n result_success=result.success,\n result_content=result.content if result.success else None,\n result_error=result.error if not result.success else None,\n )\n\n # Print result\n if result.success:\n result_text = result.content\n if len(result_text) > 300:\n result_text = result_text[:300] + f\"{Colors.DIM}...{Colors.RESET}\"\n print(f\"{Colors.BRIGHT_GREEN}✓ Result:{Colors.RESET} {result_text}\")\n else:\n print(f\"{Colors.BRIGHT_RED}✗ Error:{Colors.RESET} {Colors.RED}{result.error}{Colors.RESET}\")\n\n # Add tool result message\n tool_msg = Message(\n role=\"tool\",\n content=result.content if result.success else f\"Error: {result.error}\",\n tool_call_id=tool_call_id,\n name=function_name,\n )\n self.messages.append(tool_msg)\n\n # Check for cancellation after each tool execution\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n\n step += 1\n\n # Max steps reached\n error_msg = f\"Task couldn't be completed after {self.max_steps} steps.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {error_msg}{Colors.RESET}\")\n return error_msg\n\n def get_history(self) -> list[Message]:\n \"\"\"Get message history.\"\"\"\n return self.messages.copy()\n\n\n# Source: mini_agent/tools/file_tools.py\nclass ReadTool(Tool):\n \"\"\"Read file content.\"\"\"\n\n def __init__(self, workspace_dir: str = \".\"):\n \"\"\"Initialize ReadTool with workspace directory.\n\n Args:\n workspace_dir: Base directory for resolving relative paths\n \"\"\"\n self.workspace_dir = Path(workspace_dir).absolute()\n\n @property\n def name(self) -> str:\n return \"read_file\"\n\n @property\n def description(self) -> str:\n return (\n \"Read file contents from the filesystem. Output always includes line numbers \"\n \"in format 'LINE_NUMBER|LINE_CONTENT' (1-indexed). Supports reading partial content \"\n \"by specifying line offset and limit for large files. \"\n \"You can call this tool multiple times in parallel to read different files simultaneously.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"type\": \"string\",\n \"description\": \"Absolute or relative path to the file\",\n },\n \"offset\": {\n \"type\": \"integer\",\n \"description\": \"Starting line number (1-indexed). Use for large files to read from specific line\",\n },\n \"limit\": {\n \"type\": \"integer\",\n \"description\": \"Number of lines to read. Use with offset for large files to read in chunks\",\n },\n },\n \"required\": [\"path\"],\n }\n\n async def execute(self, path: str, offset: int | None = None, limit: int | None = None) -> ToolResult:\n \"\"\"Execute read file.\"\"\"\n try:\n file_path = Path(path)\n # Resolve relative paths relative to workspace_dir\n if not file_path.is_absolute():\n file_path = self.workspace_dir / file_path\n\n if not file_path.exists():\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"File not found: {path}\",\n )\n\n # Read file content with line numbers\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.readlines()\n\n # Apply offset and limit\n start = (offset - 1) if offset else 0\n end = (start + limit) if limit else len(lines)\n if start < 0:\n start = 0\n if end > len(lines):\n end = len(lines)\n\n selected_lines = lines[start:end]\n\n # Format with line numbers (1-indexed)\n numbered_lines = []\n for i, line in enumerate(selected_lines, start=start + 1):\n # Remove trailing newline for formatting\n line_content = line.rstrip(\"\\n\")\n numbered_lines.append(f\"{i:6d}|{line_content}\")\n\n content = \"\\n\".join(numbered_lines)\n\n # Apply token truncation if needed\n max_tokens = 32000\n content = truncate_text_by_tokens(content, max_tokens)\n\n return ToolResult(success=True, content=content)\n except Exception as e:\n return ToolResult(success=False, content=\"\", error=str(e))\n\nclass WriteTool(Tool):\n \"\"\"Write content to a file.\"\"\"\n\n def __init__(self, workspace_dir: str = \".\"):\n \"\"\"Initialize WriteTool with workspace directory.\n\n Args:\n workspace_dir: Base directory for resolving relative paths\n \"\"\"\n self.workspace_dir = Path(workspace_dir).absolute()\n\n @property\n def name(self) -> str:\n return \"write_file\"\n\n @property\n def description(self) -> str:\n return (\n \"Write content to a file. Will overwrite existing files completely. \"\n \"For existing files, you should read the file first using read_file. \"\n \"Prefer editing existing files over creating new ones unless explicitly needed.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"type\": \"string\",\n \"description\": \"Absolute or relative path to the file\",\n },\n \"content\": {\n \"type\": \"string\",\n \"description\": \"Complete content to write (will replace existing content)\",\n },\n },\n \"required\": [\"path\", \"content\"],\n }\n\n async def execute(self, path: str, content: str) -> ToolResult:\n \"\"\"Execute write file.\"\"\"\n try:\n file_path = Path(path)\n # Resolve relative paths relative to workspace_dir\n if not file_path.is_absolute():\n file_path = self.workspace_dir / file_path\n\n # Create parent directories if they don't exist\n file_path.parent.mkdir(parents=True, exist_ok=True)\n\n file_path.write_text(content, encoding=\"utf-8\")\n return ToolResult(success=True, content=f\"Successfully wrote to {file_path}\")\n except Exception as e:\n return ToolResult(success=False, content=\"\", error=str(e))\n\n\n# Source: mini_agent/tools/note_tool.py\nclass SessionNoteTool(Tool):\n \"\"\"Tool for recording and recalling session notes.\n\n The agent can use this tool to:\n - Record important facts, decisions, or context during sessions\n - Recall information from previous sessions\n - Build up knowledge over time\n\n Example usage by agent:\n - record_note(\"User prefers concise responses\")\n - record_note(\"Project uses Python 3.12 and async/await\")\n - recall_notes() -> retrieves all recorded notes\n \"\"\"\n\n def __init__(self, memory_file: str = \"./workspace/.agent_memory.json\"):\n \"\"\"Initialize session note tool.\n\n Args:\n memory_file: Path to the note storage file\n \"\"\"\n self.memory_file = Path(memory_file)\n # Lazy loading: file and directory are only created when first note is recorded\n\n @property\n def name(self) -> str:\n return \"record_note\"\n\n @property\n def description(self) -> str:\n return (\n \"Record important information as session notes for future reference. \"\n \"Use this to record key facts, user preferences, decisions, or context \"\n \"that should be recalled later in the agent execution chain. Each note is timestamped.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"content\": {\n \"type\": \"string\",\n \"description\": \"The information to record as a note. Be concise but specific.\",\n },\n \"category\": {\n \"type\": \"string\",\n \"description\": \"Optional category/tag for this note (e.g., 'user_preference', 'project_info', 'decision')\",\n },\n },\n \"required\": [\"content\"],\n }\n\n def _load_from_file(self) -> list:\n \"\"\"Load notes from file.\n \n Returns empty list if file doesn't exist (lazy loading).\n \"\"\"\n if not self.memory_file.exists():\n return []\n \n try:\n return json.loads(self.memory_file.read_text())\n except Exception:\n return []\n\n def _save_to_file(self, notes: list):\n \"\"\"Save notes to file.\n \n Creates parent directory and file if they don't exist (lazy initialization).\n \"\"\"\n # Ensure parent directory exists when actually saving\n self.memory_file.parent.mkdir(parents=True, exist_ok=True)\n self.memory_file.write_text(json.dumps(notes, indent=2, ensure_ascii=False))\n\n async def execute(self, content: str, category: str = \"general\") -> ToolResult:\n \"\"\"Record a session note.\n\n Args:\n content: The information to record\n category: Category/tag for this note\n\n Returns:\n ToolResult with success status\n \"\"\"\n try:\n # Load existing notes\n notes = self._load_from_file()\n\n # Add new note with timestamp\n note = {\n \"timestamp\": datetime.now().isoformat(),\n \"category\": category,\n \"content\": content,\n }\n notes.append(note)\n\n # Save back to file\n self._save_to_file(notes)\n\n return ToolResult(\n success=True,\n content=f\"Recorded note: {content} (category: {category})\",\n )\n except Exception as e:\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"Failed to record note: {str(e)}\",\n )", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 29731}, "tests/test_session_integration.py::90": {"resolved_imports": ["mini_agent/llm/__init__.py", "mini_agent/agent.py", "mini_agent/schema/schema.py", "mini_agent/tools/bash_tool.py", "mini_agent/tools/file_tools.py", "mini_agent/tools/note_tool.py"], "used_names": ["Agent"], "enclosing_function": "test_session_history_management", "extracted_code": "# Source: mini_agent/agent.py\nclass Agent:\n \"\"\"Single agent with basic tools and MCP support.\"\"\"\n\n def __init__(\n self,\n llm_client: LLMClient,\n system_prompt: str,\n tools: list[Tool],\n max_steps: int = 50,\n workspace_dir: str = \"./workspace\",\n token_limit: int = 80000, # Summary triggered when tokens exceed this value\n ):\n self.llm = llm_client\n self.tools = {tool.name: tool for tool in tools}\n self.max_steps = max_steps\n self.token_limit = token_limit\n self.workspace_dir = Path(workspace_dir)\n # Cancellation event for interrupting agent execution (set externally, e.g., by Esc key)\n self.cancel_event: Optional[asyncio.Event] = None\n\n # Ensure workspace exists\n self.workspace_dir.mkdir(parents=True, exist_ok=True)\n\n # Inject workspace information into system prompt if not already present\n if \"Current Workspace\" not in system_prompt:\n workspace_info = f\"\\n\\n## Current Workspace\\nYou are currently working in: `{self.workspace_dir.absolute()}`\\nAll relative paths will be resolved relative to this directory.\"\n system_prompt = system_prompt + workspace_info\n\n self.system_prompt = system_prompt\n\n # Initialize message history\n self.messages: list[Message] = [Message(role=\"system\", content=system_prompt)]\n\n # Initialize logger\n self.logger = AgentLogger()\n\n # Token usage from last API response (updated after each LLM call)\n self.api_total_tokens: int = 0\n # Flag to skip token check right after summary (avoid consecutive triggers)\n self._skip_next_token_check: bool = False\n\n def add_user_message(self, content: str):\n \"\"\"Add a user message to history.\"\"\"\n self.messages.append(Message(role=\"user\", content=content))\n\n def _check_cancelled(self) -> bool:\n \"\"\"Check if agent execution has been cancelled.\n\n Returns:\n True if cancelled, False otherwise.\n \"\"\"\n if self.cancel_event is not None and self.cancel_event.is_set():\n return True\n return False\n\n def _cleanup_incomplete_messages(self):\n \"\"\"Remove the incomplete assistant message and its partial tool results.\n\n This ensures message consistency after cancellation by removing\n only the current step's incomplete messages, preserving completed steps.\n \"\"\"\n # Find the index of the last assistant message\n last_assistant_idx = -1\n for i in range(len(self.messages) - 1, -1, -1):\n if self.messages[i].role == \"assistant\":\n last_assistant_idx = i\n break\n\n if last_assistant_idx == -1:\n # No assistant message found, nothing to clean\n return\n\n # Remove the last assistant message and all tool results after it\n removed_count = len(self.messages) - last_assistant_idx\n if removed_count > 0:\n self.messages = self.messages[:last_assistant_idx]\n print(f\"{Colors.DIM} Cleaned up {removed_count} incomplete message(s){Colors.RESET}\")\n\n def _estimate_tokens(self) -> int:\n \"\"\"Accurately calculate token count for message history using tiktoken\n\n Uses cl100k_base encoder (GPT-4/Claude/M2 compatible)\n \"\"\"\n try:\n # Use cl100k_base encoder (used by GPT-4 and most modern models)\n encoding = tiktoken.get_encoding(\"cl100k_base\")\n except Exception:\n # Fallback: if tiktoken initialization fails, use simple estimation\n return self._estimate_tokens_fallback()\n\n total_tokens = 0\n\n for msg in self.messages:\n # Count text content\n if isinstance(msg.content, str):\n total_tokens += len(encoding.encode(msg.content))\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n # Convert dict to string for calculation\n total_tokens += len(encoding.encode(str(block)))\n\n # Count thinking\n if msg.thinking:\n total_tokens += len(encoding.encode(msg.thinking))\n\n # Count tool_calls\n if msg.tool_calls:\n total_tokens += len(encoding.encode(str(msg.tool_calls)))\n\n # Metadata overhead per message (approximately 4 tokens)\n total_tokens += 4\n\n return total_tokens\n\n def _estimate_tokens_fallback(self) -> int:\n \"\"\"Fallback token estimation method (when tiktoken is unavailable)\"\"\"\n total_chars = 0\n for msg in self.messages:\n if isinstance(msg.content, str):\n total_chars += len(msg.content)\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n total_chars += len(str(block))\n\n if msg.thinking:\n total_chars += len(msg.thinking)\n\n if msg.tool_calls:\n total_chars += len(str(msg.tool_calls))\n\n # Rough estimation: average 2.5 characters = 1 token\n return int(total_chars / 2.5)\n\n async def _summarize_messages(self):\n \"\"\"Message history summarization: summarize conversations between user messages when tokens exceed limit\n\n Strategy (Agent mode):\n - Keep all user messages (these are user intents)\n - Summarize content between each user-user pair (agent execution process)\n - If last round is still executing (has agent/tool messages but no next user), also summarize\n - Structure: system -> user1 -> summary1 -> user2 -> summary2 -> user3 -> summary3 (if executing)\n\n Summary is triggered when EITHER:\n - Local token estimation exceeds limit\n - API reported total_tokens exceeds limit\n \"\"\"\n # Skip check if we just completed a summary (wait for next LLM call to update api_total_tokens)\n if self._skip_next_token_check:\n self._skip_next_token_check = False\n return\n\n estimated_tokens = self._estimate_tokens()\n\n # Check both local estimation and API reported tokens\n should_summarize = estimated_tokens > self.token_limit or self.api_total_tokens > self.token_limit\n\n # If neither exceeded, no summary needed\n if not should_summarize:\n return\n\n print(\n f\"\\n{Colors.BRIGHT_YELLOW}📊 Token usage - Local estimate: {estimated_tokens}, API reported: {self.api_total_tokens}, Limit: {self.token_limit}{Colors.RESET}\"\n )\n print(f\"{Colors.BRIGHT_YELLOW}🔄 Triggering message history summarization...{Colors.RESET}\")\n\n # Find all user message indices (skip system prompt)\n user_indices = [i for i, msg in enumerate(self.messages) if msg.role == \"user\" and i > 0]\n\n # Need at least 1 user message to perform summary\n if len(user_indices) < 1:\n print(f\"{Colors.BRIGHT_YELLOW}⚠️ Insufficient messages, cannot summarize{Colors.RESET}\")\n return\n\n # Build new message list\n new_messages = [self.messages[0]] # Keep system prompt\n summary_count = 0\n\n # Iterate through each user message and summarize the execution process after it\n for i, user_idx in enumerate(user_indices):\n # Add current user message\n new_messages.append(self.messages[user_idx])\n\n # Determine message range to summarize\n # If last user, go to end of message list; otherwise to before next user\n if i < len(user_indices) - 1:\n next_user_idx = user_indices[i + 1]\n else:\n next_user_idx = len(self.messages)\n\n # Extract execution messages for this round\n execution_messages = self.messages[user_idx + 1 : next_user_idx]\n\n # If there are execution messages in this round, summarize them\n if execution_messages:\n summary_text = await self._create_summary(execution_messages, i + 1)\n if summary_text:\n summary_message = Message(\n role=\"user\",\n content=f\"[Assistant Execution Summary]\\n\\n{summary_text}\",\n )\n new_messages.append(summary_message)\n summary_count += 1\n\n # Replace message list\n self.messages = new_messages\n\n # Skip next token check to avoid consecutive summary triggers\n # (api_total_tokens will be updated after next LLM call)\n self._skip_next_token_check = True\n\n new_tokens = self._estimate_tokens()\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary completed, local tokens: {estimated_tokens} → {new_tokens}{Colors.RESET}\")\n print(f\"{Colors.DIM} Structure: system + {len(user_indices)} user messages + {summary_count} summaries{Colors.RESET}\")\n print(f\"{Colors.DIM} Note: API token count will update on next LLM call{Colors.RESET}\")\n\n async def _create_summary(self, messages: list[Message], round_num: int) -> str:\n \"\"\"Create summary for one execution round\n\n Args:\n messages: List of messages to summarize\n round_num: Round number\n\n Returns:\n Summary text\n \"\"\"\n if not messages:\n return \"\"\n\n # Build summary content\n summary_content = f\"Round {round_num} execution process:\\n\\n\"\n for msg in messages:\n if msg.role == \"assistant\":\n content_text = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\"Assistant: {content_text}\\n\"\n if msg.tool_calls:\n tool_names = [tc.function.name for tc in msg.tool_calls]\n summary_content += f\" → Called tools: {', '.join(tool_names)}\\n\"\n elif msg.role == \"tool\":\n result_preview = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\" ← Tool returned: {result_preview}...\\n\"\n\n # Call LLM to generate concise summary\n try:\n summary_prompt = f\"\"\"Please provide a concise summary of the following Agent execution process:\n\n{summary_content}\n\nRequirements:\n1. Focus on what tasks were completed and which tools were called\n2. Keep key execution results and important findings\n3. Be concise and clear, within 1000 words\n4. Use English\n5. Do not include \"user\" related content, only summarize the Agent's execution process\"\"\"\n\n summary_msg = Message(role=\"user\", content=summary_prompt)\n response = await self.llm.generate(\n messages=[\n Message(\n role=\"system\",\n content=\"You are an assistant skilled at summarizing Agent execution processes.\",\n ),\n summary_msg,\n ]\n )\n\n summary_text = response.content\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary for round {round_num} generated successfully{Colors.RESET}\")\n return summary_text\n\n except Exception as e:\n print(f\"{Colors.BRIGHT_RED}✗ Summary generation failed for round {round_num}: {e}{Colors.RESET}\")\n # Use simple text summary on failure\n return summary_content\n\n async def run(self, cancel_event: Optional[asyncio.Event] = None) -> str:\n \"\"\"Execute agent loop until task is complete or max steps reached.\n\n Args:\n cancel_event: Optional asyncio.Event that can be set to cancel execution.\n When set, the agent will stop at the next safe checkpoint\n (after completing the current step to keep messages consistent).\n\n Returns:\n The final response content, or error message (including cancellation message).\n \"\"\"\n # Set cancellation event (can also be set via self.cancel_event before calling run())\n if cancel_event is not None:\n self.cancel_event = cancel_event\n\n # Start new run, initialize log file\n self.logger.start_new_run()\n print(f\"{Colors.DIM}📝 Log file: {self.logger.get_log_file_path()}{Colors.RESET}\")\n\n step = 0\n run_start_time = perf_counter()\n\n while step < self.max_steps:\n # Check for cancellation at start of each step\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_start_time = perf_counter()\n # Check and summarize message history to prevent context overflow\n await self._summarize_messages()\n\n # Step header with proper width calculation\n BOX_WIDTH = 58\n step_text = f\"{Colors.BOLD}{Colors.BRIGHT_CYAN}💭 Step {step + 1}/{self.max_steps}{Colors.RESET}\"\n step_display_width = calculate_display_width(step_text)\n padding = max(0, BOX_WIDTH - 1 - step_display_width) # -1 for leading space\n\n print(f\"\\n{Colors.DIM}╭{'─' * BOX_WIDTH}╮{Colors.RESET}\")\n print(f\"{Colors.DIM}│{Colors.RESET} {step_text}{' ' * padding}{Colors.DIM}│{Colors.RESET}\")\n print(f\"{Colors.DIM}╰{'─' * BOX_WIDTH}╯{Colors.RESET}\")\n\n # Get tool list for LLM call\n tool_list = list(self.tools.values())\n\n # Log LLM request and call LLM with Tool objects directly\n self.logger.log_request(messages=self.messages, tools=tool_list)\n\n try:\n response = await self.llm.generate(messages=self.messages, tools=tool_list)\n except Exception as e:\n # Check if it's a retry exhausted error\n from .retry import RetryExhaustedError\n\n if isinstance(e, RetryExhaustedError):\n error_msg = f\"LLM call failed after {e.attempts} retries\\nLast error: {str(e.last_exception)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Retry failed:{Colors.RESET} {error_msg}\")\n else:\n error_msg = f\"LLM call failed: {str(e)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Error:{Colors.RESET} {error_msg}\")\n return error_msg\n\n # Accumulate API reported token usage\n if response.usage:\n self.api_total_tokens = response.usage.total_tokens\n\n # Log LLM response\n self.logger.log_response(\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n finish_reason=response.finish_reason,\n )\n\n # Add assistant message\n assistant_msg = Message(\n role=\"assistant\",\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n )\n self.messages.append(assistant_msg)\n\n # Print thinking if present\n if response.thinking:\n print(f\"\\n{Colors.BOLD}{Colors.MAGENTA}🧠 Thinking:{Colors.RESET}\")\n print(f\"{Colors.DIM}{response.thinking}{Colors.RESET}\")\n\n # Print assistant response\n if response.content:\n print(f\"\\n{Colors.BOLD}{Colors.BRIGHT_BLUE}🤖 Assistant:{Colors.RESET}\")\n print(f\"{response.content}\")\n\n # Check if task is complete (no tool calls)\n if not response.tool_calls:\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n return response.content\n\n # Check for cancellation before executing tools\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n # Execute tool calls\n for tool_call in response.tool_calls:\n tool_call_id = tool_call.id\n function_name = tool_call.function.name\n arguments = tool_call.function.arguments\n\n # Tool call header\n print(f\"\\n{Colors.BRIGHT_YELLOW}🔧 Tool Call:{Colors.RESET} {Colors.BOLD}{Colors.CYAN}{function_name}{Colors.RESET}\")\n\n # Arguments (formatted display)\n print(f\"{Colors.DIM} Arguments:{Colors.RESET}\")\n # Truncate each argument value to avoid overly long output\n truncated_args = {}\n for key, value in arguments.items():\n value_str = str(value)\n if len(value_str) > 200:\n truncated_args[key] = value_str[:200] + \"...\"\n else:\n truncated_args[key] = value\n args_json = json.dumps(truncated_args, indent=2, ensure_ascii=False)\n for line in args_json.split(\"\\n\"):\n print(f\" {Colors.DIM}{line}{Colors.RESET}\")\n\n # Execute tool\n if function_name not in self.tools:\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Unknown tool: {function_name}\",\n )\n else:\n try:\n tool = self.tools[function_name]\n result = await tool.execute(**arguments)\n except Exception as e:\n # Catch all exceptions during tool execution, convert to failed ToolResult\n import traceback\n\n error_detail = f\"{type(e).__name__}: {str(e)}\"\n error_trace = traceback.format_exc()\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Tool execution failed: {error_detail}\\n\\nTraceback:\\n{error_trace}\",\n )\n\n # Log tool execution result\n self.logger.log_tool_result(\n tool_name=function_name,\n arguments=arguments,\n result_success=result.success,\n result_content=result.content if result.success else None,\n result_error=result.error if not result.success else None,\n )\n\n # Print result\n if result.success:\n result_text = result.content\n if len(result_text) > 300:\n result_text = result_text[:300] + f\"{Colors.DIM}...{Colors.RESET}\"\n print(f\"{Colors.BRIGHT_GREEN}✓ Result:{Colors.RESET} {result_text}\")\n else:\n print(f\"{Colors.BRIGHT_RED}✗ Error:{Colors.RESET} {Colors.RED}{result.error}{Colors.RESET}\")\n\n # Add tool result message\n tool_msg = Message(\n role=\"tool\",\n content=result.content if result.success else f\"Error: {result.error}\",\n tool_call_id=tool_call_id,\n name=function_name,\n )\n self.messages.append(tool_msg)\n\n # Check for cancellation after each tool execution\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n\n step += 1\n\n # Max steps reached\n error_msg = f\"Task couldn't be completed after {self.max_steps} steps.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {error_msg}{Colors.RESET}\")\n return error_msg\n\n def get_history(self) -> list[Message]:\n \"\"\"Get message history.\"\"\"\n return self.messages.copy()", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 20770}, "tests/test_session_integration.py::171": {"resolved_imports": ["mini_agent/llm/__init__.py", "mini_agent/agent.py", "mini_agent/schema/schema.py", "mini_agent/tools/bash_tool.py", "mini_agent/tools/file_tools.py", "mini_agent/tools/note_tool.py"], "used_names": ["Agent", "Message"], "enclosing_function": "test_message_statistics", "extracted_code": "# Source: mini_agent/agent.py\nclass Agent:\n \"\"\"Single agent with basic tools and MCP support.\"\"\"\n\n def __init__(\n self,\n llm_client: LLMClient,\n system_prompt: str,\n tools: list[Tool],\n max_steps: int = 50,\n workspace_dir: str = \"./workspace\",\n token_limit: int = 80000, # Summary triggered when tokens exceed this value\n ):\n self.llm = llm_client\n self.tools = {tool.name: tool for tool in tools}\n self.max_steps = max_steps\n self.token_limit = token_limit\n self.workspace_dir = Path(workspace_dir)\n # Cancellation event for interrupting agent execution (set externally, e.g., by Esc key)\n self.cancel_event: Optional[asyncio.Event] = None\n\n # Ensure workspace exists\n self.workspace_dir.mkdir(parents=True, exist_ok=True)\n\n # Inject workspace information into system prompt if not already present\n if \"Current Workspace\" not in system_prompt:\n workspace_info = f\"\\n\\n## Current Workspace\\nYou are currently working in: `{self.workspace_dir.absolute()}`\\nAll relative paths will be resolved relative to this directory.\"\n system_prompt = system_prompt + workspace_info\n\n self.system_prompt = system_prompt\n\n # Initialize message history\n self.messages: list[Message] = [Message(role=\"system\", content=system_prompt)]\n\n # Initialize logger\n self.logger = AgentLogger()\n\n # Token usage from last API response (updated after each LLM call)\n self.api_total_tokens: int = 0\n # Flag to skip token check right after summary (avoid consecutive triggers)\n self._skip_next_token_check: bool = False\n\n def add_user_message(self, content: str):\n \"\"\"Add a user message to history.\"\"\"\n self.messages.append(Message(role=\"user\", content=content))\n\n def _check_cancelled(self) -> bool:\n \"\"\"Check if agent execution has been cancelled.\n\n Returns:\n True if cancelled, False otherwise.\n \"\"\"\n if self.cancel_event is not None and self.cancel_event.is_set():\n return True\n return False\n\n def _cleanup_incomplete_messages(self):\n \"\"\"Remove the incomplete assistant message and its partial tool results.\n\n This ensures message consistency after cancellation by removing\n only the current step's incomplete messages, preserving completed steps.\n \"\"\"\n # Find the index of the last assistant message\n last_assistant_idx = -1\n for i in range(len(self.messages) - 1, -1, -1):\n if self.messages[i].role == \"assistant\":\n last_assistant_idx = i\n break\n\n if last_assistant_idx == -1:\n # No assistant message found, nothing to clean\n return\n\n # Remove the last assistant message and all tool results after it\n removed_count = len(self.messages) - last_assistant_idx\n if removed_count > 0:\n self.messages = self.messages[:last_assistant_idx]\n print(f\"{Colors.DIM} Cleaned up {removed_count} incomplete message(s){Colors.RESET}\")\n\n def _estimate_tokens(self) -> int:\n \"\"\"Accurately calculate token count for message history using tiktoken\n\n Uses cl100k_base encoder (GPT-4/Claude/M2 compatible)\n \"\"\"\n try:\n # Use cl100k_base encoder (used by GPT-4 and most modern models)\n encoding = tiktoken.get_encoding(\"cl100k_base\")\n except Exception:\n # Fallback: if tiktoken initialization fails, use simple estimation\n return self._estimate_tokens_fallback()\n\n total_tokens = 0\n\n for msg in self.messages:\n # Count text content\n if isinstance(msg.content, str):\n total_tokens += len(encoding.encode(msg.content))\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n # Convert dict to string for calculation\n total_tokens += len(encoding.encode(str(block)))\n\n # Count thinking\n if msg.thinking:\n total_tokens += len(encoding.encode(msg.thinking))\n\n # Count tool_calls\n if msg.tool_calls:\n total_tokens += len(encoding.encode(str(msg.tool_calls)))\n\n # Metadata overhead per message (approximately 4 tokens)\n total_tokens += 4\n\n return total_tokens\n\n def _estimate_tokens_fallback(self) -> int:\n \"\"\"Fallback token estimation method (when tiktoken is unavailable)\"\"\"\n total_chars = 0\n for msg in self.messages:\n if isinstance(msg.content, str):\n total_chars += len(msg.content)\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n total_chars += len(str(block))\n\n if msg.thinking:\n total_chars += len(msg.thinking)\n\n if msg.tool_calls:\n total_chars += len(str(msg.tool_calls))\n\n # Rough estimation: average 2.5 characters = 1 token\n return int(total_chars / 2.5)\n\n async def _summarize_messages(self):\n \"\"\"Message history summarization: summarize conversations between user messages when tokens exceed limit\n\n Strategy (Agent mode):\n - Keep all user messages (these are user intents)\n - Summarize content between each user-user pair (agent execution process)\n - If last round is still executing (has agent/tool messages but no next user), also summarize\n - Structure: system -> user1 -> summary1 -> user2 -> summary2 -> user3 -> summary3 (if executing)\n\n Summary is triggered when EITHER:\n - Local token estimation exceeds limit\n - API reported total_tokens exceeds limit\n \"\"\"\n # Skip check if we just completed a summary (wait for next LLM call to update api_total_tokens)\n if self._skip_next_token_check:\n self._skip_next_token_check = False\n return\n\n estimated_tokens = self._estimate_tokens()\n\n # Check both local estimation and API reported tokens\n should_summarize = estimated_tokens > self.token_limit or self.api_total_tokens > self.token_limit\n\n # If neither exceeded, no summary needed\n if not should_summarize:\n return\n\n print(\n f\"\\n{Colors.BRIGHT_YELLOW}📊 Token usage - Local estimate: {estimated_tokens}, API reported: {self.api_total_tokens}, Limit: {self.token_limit}{Colors.RESET}\"\n )\n print(f\"{Colors.BRIGHT_YELLOW}🔄 Triggering message history summarization...{Colors.RESET}\")\n\n # Find all user message indices (skip system prompt)\n user_indices = [i for i, msg in enumerate(self.messages) if msg.role == \"user\" and i > 0]\n\n # Need at least 1 user message to perform summary\n if len(user_indices) < 1:\n print(f\"{Colors.BRIGHT_YELLOW}⚠️ Insufficient messages, cannot summarize{Colors.RESET}\")\n return\n\n # Build new message list\n new_messages = [self.messages[0]] # Keep system prompt\n summary_count = 0\n\n # Iterate through each user message and summarize the execution process after it\n for i, user_idx in enumerate(user_indices):\n # Add current user message\n new_messages.append(self.messages[user_idx])\n\n # Determine message range to summarize\n # If last user, go to end of message list; otherwise to before next user\n if i < len(user_indices) - 1:\n next_user_idx = user_indices[i + 1]\n else:\n next_user_idx = len(self.messages)\n\n # Extract execution messages for this round\n execution_messages = self.messages[user_idx + 1 : next_user_idx]\n\n # If there are execution messages in this round, summarize them\n if execution_messages:\n summary_text = await self._create_summary(execution_messages, i + 1)\n if summary_text:\n summary_message = Message(\n role=\"user\",\n content=f\"[Assistant Execution Summary]\\n\\n{summary_text}\",\n )\n new_messages.append(summary_message)\n summary_count += 1\n\n # Replace message list\n self.messages = new_messages\n\n # Skip next token check to avoid consecutive summary triggers\n # (api_total_tokens will be updated after next LLM call)\n self._skip_next_token_check = True\n\n new_tokens = self._estimate_tokens()\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary completed, local tokens: {estimated_tokens} → {new_tokens}{Colors.RESET}\")\n print(f\"{Colors.DIM} Structure: system + {len(user_indices)} user messages + {summary_count} summaries{Colors.RESET}\")\n print(f\"{Colors.DIM} Note: API token count will update on next LLM call{Colors.RESET}\")\n\n async def _create_summary(self, messages: list[Message], round_num: int) -> str:\n \"\"\"Create summary for one execution round\n\n Args:\n messages: List of messages to summarize\n round_num: Round number\n\n Returns:\n Summary text\n \"\"\"\n if not messages:\n return \"\"\n\n # Build summary content\n summary_content = f\"Round {round_num} execution process:\\n\\n\"\n for msg in messages:\n if msg.role == \"assistant\":\n content_text = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\"Assistant: {content_text}\\n\"\n if msg.tool_calls:\n tool_names = [tc.function.name for tc in msg.tool_calls]\n summary_content += f\" → Called tools: {', '.join(tool_names)}\\n\"\n elif msg.role == \"tool\":\n result_preview = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\" ← Tool returned: {result_preview}...\\n\"\n\n # Call LLM to generate concise summary\n try:\n summary_prompt = f\"\"\"Please provide a concise summary of the following Agent execution process:\n\n{summary_content}\n\nRequirements:\n1. Focus on what tasks were completed and which tools were called\n2. Keep key execution results and important findings\n3. Be concise and clear, within 1000 words\n4. Use English\n5. Do not include \"user\" related content, only summarize the Agent's execution process\"\"\"\n\n summary_msg = Message(role=\"user\", content=summary_prompt)\n response = await self.llm.generate(\n messages=[\n Message(\n role=\"system\",\n content=\"You are an assistant skilled at summarizing Agent execution processes.\",\n ),\n summary_msg,\n ]\n )\n\n summary_text = response.content\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary for round {round_num} generated successfully{Colors.RESET}\")\n return summary_text\n\n except Exception as e:\n print(f\"{Colors.BRIGHT_RED}✗ Summary generation failed for round {round_num}: {e}{Colors.RESET}\")\n # Use simple text summary on failure\n return summary_content\n\n async def run(self, cancel_event: Optional[asyncio.Event] = None) -> str:\n \"\"\"Execute agent loop until task is complete or max steps reached.\n\n Args:\n cancel_event: Optional asyncio.Event that can be set to cancel execution.\n When set, the agent will stop at the next safe checkpoint\n (after completing the current step to keep messages consistent).\n\n Returns:\n The final response content, or error message (including cancellation message).\n \"\"\"\n # Set cancellation event (can also be set via self.cancel_event before calling run())\n if cancel_event is not None:\n self.cancel_event = cancel_event\n\n # Start new run, initialize log file\n self.logger.start_new_run()\n print(f\"{Colors.DIM}📝 Log file: {self.logger.get_log_file_path()}{Colors.RESET}\")\n\n step = 0\n run_start_time = perf_counter()\n\n while step < self.max_steps:\n # Check for cancellation at start of each step\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_start_time = perf_counter()\n # Check and summarize message history to prevent context overflow\n await self._summarize_messages()\n\n # Step header with proper width calculation\n BOX_WIDTH = 58\n step_text = f\"{Colors.BOLD}{Colors.BRIGHT_CYAN}💭 Step {step + 1}/{self.max_steps}{Colors.RESET}\"\n step_display_width = calculate_display_width(step_text)\n padding = max(0, BOX_WIDTH - 1 - step_display_width) # -1 for leading space\n\n print(f\"\\n{Colors.DIM}╭{'─' * BOX_WIDTH}╮{Colors.RESET}\")\n print(f\"{Colors.DIM}│{Colors.RESET} {step_text}{' ' * padding}{Colors.DIM}│{Colors.RESET}\")\n print(f\"{Colors.DIM}╰{'─' * BOX_WIDTH}╯{Colors.RESET}\")\n\n # Get tool list for LLM call\n tool_list = list(self.tools.values())\n\n # Log LLM request and call LLM with Tool objects directly\n self.logger.log_request(messages=self.messages, tools=tool_list)\n\n try:\n response = await self.llm.generate(messages=self.messages, tools=tool_list)\n except Exception as e:\n # Check if it's a retry exhausted error\n from .retry import RetryExhaustedError\n\n if isinstance(e, RetryExhaustedError):\n error_msg = f\"LLM call failed after {e.attempts} retries\\nLast error: {str(e.last_exception)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Retry failed:{Colors.RESET} {error_msg}\")\n else:\n error_msg = f\"LLM call failed: {str(e)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Error:{Colors.RESET} {error_msg}\")\n return error_msg\n\n # Accumulate API reported token usage\n if response.usage:\n self.api_total_tokens = response.usage.total_tokens\n\n # Log LLM response\n self.logger.log_response(\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n finish_reason=response.finish_reason,\n )\n\n # Add assistant message\n assistant_msg = Message(\n role=\"assistant\",\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n )\n self.messages.append(assistant_msg)\n\n # Print thinking if present\n if response.thinking:\n print(f\"\\n{Colors.BOLD}{Colors.MAGENTA}🧠 Thinking:{Colors.RESET}\")\n print(f\"{Colors.DIM}{response.thinking}{Colors.RESET}\")\n\n # Print assistant response\n if response.content:\n print(f\"\\n{Colors.BOLD}{Colors.BRIGHT_BLUE}🤖 Assistant:{Colors.RESET}\")\n print(f\"{response.content}\")\n\n # Check if task is complete (no tool calls)\n if not response.tool_calls:\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n return response.content\n\n # Check for cancellation before executing tools\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n # Execute tool calls\n for tool_call in response.tool_calls:\n tool_call_id = tool_call.id\n function_name = tool_call.function.name\n arguments = tool_call.function.arguments\n\n # Tool call header\n print(f\"\\n{Colors.BRIGHT_YELLOW}🔧 Tool Call:{Colors.RESET} {Colors.BOLD}{Colors.CYAN}{function_name}{Colors.RESET}\")\n\n # Arguments (formatted display)\n print(f\"{Colors.DIM} Arguments:{Colors.RESET}\")\n # Truncate each argument value to avoid overly long output\n truncated_args = {}\n for key, value in arguments.items():\n value_str = str(value)\n if len(value_str) > 200:\n truncated_args[key] = value_str[:200] + \"...\"\n else:\n truncated_args[key] = value\n args_json = json.dumps(truncated_args, indent=2, ensure_ascii=False)\n for line in args_json.split(\"\\n\"):\n print(f\" {Colors.DIM}{line}{Colors.RESET}\")\n\n # Execute tool\n if function_name not in self.tools:\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Unknown tool: {function_name}\",\n )\n else:\n try:\n tool = self.tools[function_name]\n result = await tool.execute(**arguments)\n except Exception as e:\n # Catch all exceptions during tool execution, convert to failed ToolResult\n import traceback\n\n error_detail = f\"{type(e).__name__}: {str(e)}\"\n error_trace = traceback.format_exc()\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Tool execution failed: {error_detail}\\n\\nTraceback:\\n{error_trace}\",\n )\n\n # Log tool execution result\n self.logger.log_tool_result(\n tool_name=function_name,\n arguments=arguments,\n result_success=result.success,\n result_content=result.content if result.success else None,\n result_error=result.error if not result.success else None,\n )\n\n # Print result\n if result.success:\n result_text = result.content\n if len(result_text) > 300:\n result_text = result_text[:300] + f\"{Colors.DIM}...{Colors.RESET}\"\n print(f\"{Colors.BRIGHT_GREEN}✓ Result:{Colors.RESET} {result_text}\")\n else:\n print(f\"{Colors.BRIGHT_RED}✗ Error:{Colors.RESET} {Colors.RED}{result.error}{Colors.RESET}\")\n\n # Add tool result message\n tool_msg = Message(\n role=\"tool\",\n content=result.content if result.success else f\"Error: {result.error}\",\n tool_call_id=tool_call_id,\n name=function_name,\n )\n self.messages.append(tool_msg)\n\n # Check for cancellation after each tool execution\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n\n step += 1\n\n # Max steps reached\n error_msg = f\"Task couldn't be completed after {self.max_steps} steps.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {error_msg}{Colors.RESET}\")\n return error_msg\n\n def get_history(self) -> list[Message]:\n \"\"\"Get message history.\"\"\"\n return self.messages.copy()\n\n\n# Source: mini_agent/schema/schema.py\nclass Message(BaseModel):\n \"\"\"Chat message.\"\"\"\n\n role: str # \"system\", \"user\", \"assistant\", \"tool\"\n content: str | list[dict[str, Any]] # Can be string or list of content blocks\n thinking: str | None = None # Extended thinking content for assistant messages\n tool_calls: list[ToolCall] | None = None\n tool_call_id: str | None = None\n name: str | None = None", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 21192}, "tests/test_session_integration.py::61": {"resolved_imports": ["mini_agent/llm/__init__.py", "mini_agent/agent.py", "mini_agent/schema/schema.py", "mini_agent/tools/bash_tool.py", "mini_agent/tools/file_tools.py", "mini_agent/tools/note_tool.py"], "used_names": ["Agent", "ReadTool", "SessionNoteTool", "WriteTool"], "enclosing_function": "test_multi_turn_conversation", "extracted_code": "# Source: mini_agent/agent.py\nclass Agent:\n \"\"\"Single agent with basic tools and MCP support.\"\"\"\n\n def __init__(\n self,\n llm_client: LLMClient,\n system_prompt: str,\n tools: list[Tool],\n max_steps: int = 50,\n workspace_dir: str = \"./workspace\",\n token_limit: int = 80000, # Summary triggered when tokens exceed this value\n ):\n self.llm = llm_client\n self.tools = {tool.name: tool for tool in tools}\n self.max_steps = max_steps\n self.token_limit = token_limit\n self.workspace_dir = Path(workspace_dir)\n # Cancellation event for interrupting agent execution (set externally, e.g., by Esc key)\n self.cancel_event: Optional[asyncio.Event] = None\n\n # Ensure workspace exists\n self.workspace_dir.mkdir(parents=True, exist_ok=True)\n\n # Inject workspace information into system prompt if not already present\n if \"Current Workspace\" not in system_prompt:\n workspace_info = f\"\\n\\n## Current Workspace\\nYou are currently working in: `{self.workspace_dir.absolute()}`\\nAll relative paths will be resolved relative to this directory.\"\n system_prompt = system_prompt + workspace_info\n\n self.system_prompt = system_prompt\n\n # Initialize message history\n self.messages: list[Message] = [Message(role=\"system\", content=system_prompt)]\n\n # Initialize logger\n self.logger = AgentLogger()\n\n # Token usage from last API response (updated after each LLM call)\n self.api_total_tokens: int = 0\n # Flag to skip token check right after summary (avoid consecutive triggers)\n self._skip_next_token_check: bool = False\n\n def add_user_message(self, content: str):\n \"\"\"Add a user message to history.\"\"\"\n self.messages.append(Message(role=\"user\", content=content))\n\n def _check_cancelled(self) -> bool:\n \"\"\"Check if agent execution has been cancelled.\n\n Returns:\n True if cancelled, False otherwise.\n \"\"\"\n if self.cancel_event is not None and self.cancel_event.is_set():\n return True\n return False\n\n def _cleanup_incomplete_messages(self):\n \"\"\"Remove the incomplete assistant message and its partial tool results.\n\n This ensures message consistency after cancellation by removing\n only the current step's incomplete messages, preserving completed steps.\n \"\"\"\n # Find the index of the last assistant message\n last_assistant_idx = -1\n for i in range(len(self.messages) - 1, -1, -1):\n if self.messages[i].role == \"assistant\":\n last_assistant_idx = i\n break\n\n if last_assistant_idx == -1:\n # No assistant message found, nothing to clean\n return\n\n # Remove the last assistant message and all tool results after it\n removed_count = len(self.messages) - last_assistant_idx\n if removed_count > 0:\n self.messages = self.messages[:last_assistant_idx]\n print(f\"{Colors.DIM} Cleaned up {removed_count} incomplete message(s){Colors.RESET}\")\n\n def _estimate_tokens(self) -> int:\n \"\"\"Accurately calculate token count for message history using tiktoken\n\n Uses cl100k_base encoder (GPT-4/Claude/M2 compatible)\n \"\"\"\n try:\n # Use cl100k_base encoder (used by GPT-4 and most modern models)\n encoding = tiktoken.get_encoding(\"cl100k_base\")\n except Exception:\n # Fallback: if tiktoken initialization fails, use simple estimation\n return self._estimate_tokens_fallback()\n\n total_tokens = 0\n\n for msg in self.messages:\n # Count text content\n if isinstance(msg.content, str):\n total_tokens += len(encoding.encode(msg.content))\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n # Convert dict to string for calculation\n total_tokens += len(encoding.encode(str(block)))\n\n # Count thinking\n if msg.thinking:\n total_tokens += len(encoding.encode(msg.thinking))\n\n # Count tool_calls\n if msg.tool_calls:\n total_tokens += len(encoding.encode(str(msg.tool_calls)))\n\n # Metadata overhead per message (approximately 4 tokens)\n total_tokens += 4\n\n return total_tokens\n\n def _estimate_tokens_fallback(self) -> int:\n \"\"\"Fallback token estimation method (when tiktoken is unavailable)\"\"\"\n total_chars = 0\n for msg in self.messages:\n if isinstance(msg.content, str):\n total_chars += len(msg.content)\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n total_chars += len(str(block))\n\n if msg.thinking:\n total_chars += len(msg.thinking)\n\n if msg.tool_calls:\n total_chars += len(str(msg.tool_calls))\n\n # Rough estimation: average 2.5 characters = 1 token\n return int(total_chars / 2.5)\n\n async def _summarize_messages(self):\n \"\"\"Message history summarization: summarize conversations between user messages when tokens exceed limit\n\n Strategy (Agent mode):\n - Keep all user messages (these are user intents)\n - Summarize content between each user-user pair (agent execution process)\n - If last round is still executing (has agent/tool messages but no next user), also summarize\n - Structure: system -> user1 -> summary1 -> user2 -> summary2 -> user3 -> summary3 (if executing)\n\n Summary is triggered when EITHER:\n - Local token estimation exceeds limit\n - API reported total_tokens exceeds limit\n \"\"\"\n # Skip check if we just completed a summary (wait for next LLM call to update api_total_tokens)\n if self._skip_next_token_check:\n self._skip_next_token_check = False\n return\n\n estimated_tokens = self._estimate_tokens()\n\n # Check both local estimation and API reported tokens\n should_summarize = estimated_tokens > self.token_limit or self.api_total_tokens > self.token_limit\n\n # If neither exceeded, no summary needed\n if not should_summarize:\n return\n\n print(\n f\"\\n{Colors.BRIGHT_YELLOW}📊 Token usage - Local estimate: {estimated_tokens}, API reported: {self.api_total_tokens}, Limit: {self.token_limit}{Colors.RESET}\"\n )\n print(f\"{Colors.BRIGHT_YELLOW}🔄 Triggering message history summarization...{Colors.RESET}\")\n\n # Find all user message indices (skip system prompt)\n user_indices = [i for i, msg in enumerate(self.messages) if msg.role == \"user\" and i > 0]\n\n # Need at least 1 user message to perform summary\n if len(user_indices) < 1:\n print(f\"{Colors.BRIGHT_YELLOW}⚠️ Insufficient messages, cannot summarize{Colors.RESET}\")\n return\n\n # Build new message list\n new_messages = [self.messages[0]] # Keep system prompt\n summary_count = 0\n\n # Iterate through each user message and summarize the execution process after it\n for i, user_idx in enumerate(user_indices):\n # Add current user message\n new_messages.append(self.messages[user_idx])\n\n # Determine message range to summarize\n # If last user, go to end of message list; otherwise to before next user\n if i < len(user_indices) - 1:\n next_user_idx = user_indices[i + 1]\n else:\n next_user_idx = len(self.messages)\n\n # Extract execution messages for this round\n execution_messages = self.messages[user_idx + 1 : next_user_idx]\n\n # If there are execution messages in this round, summarize them\n if execution_messages:\n summary_text = await self._create_summary(execution_messages, i + 1)\n if summary_text:\n summary_message = Message(\n role=\"user\",\n content=f\"[Assistant Execution Summary]\\n\\n{summary_text}\",\n )\n new_messages.append(summary_message)\n summary_count += 1\n\n # Replace message list\n self.messages = new_messages\n\n # Skip next token check to avoid consecutive summary triggers\n # (api_total_tokens will be updated after next LLM call)\n self._skip_next_token_check = True\n\n new_tokens = self._estimate_tokens()\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary completed, local tokens: {estimated_tokens} → {new_tokens}{Colors.RESET}\")\n print(f\"{Colors.DIM} Structure: system + {len(user_indices)} user messages + {summary_count} summaries{Colors.RESET}\")\n print(f\"{Colors.DIM} Note: API token count will update on next LLM call{Colors.RESET}\")\n\n async def _create_summary(self, messages: list[Message], round_num: int) -> str:\n \"\"\"Create summary for one execution round\n\n Args:\n messages: List of messages to summarize\n round_num: Round number\n\n Returns:\n Summary text\n \"\"\"\n if not messages:\n return \"\"\n\n # Build summary content\n summary_content = f\"Round {round_num} execution process:\\n\\n\"\n for msg in messages:\n if msg.role == \"assistant\":\n content_text = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\"Assistant: {content_text}\\n\"\n if msg.tool_calls:\n tool_names = [tc.function.name for tc in msg.tool_calls]\n summary_content += f\" → Called tools: {', '.join(tool_names)}\\n\"\n elif msg.role == \"tool\":\n result_preview = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\" ← Tool returned: {result_preview}...\\n\"\n\n # Call LLM to generate concise summary\n try:\n summary_prompt = f\"\"\"Please provide a concise summary of the following Agent execution process:\n\n{summary_content}\n\nRequirements:\n1. Focus on what tasks were completed and which tools were called\n2. Keep key execution results and important findings\n3. Be concise and clear, within 1000 words\n4. Use English\n5. Do not include \"user\" related content, only summarize the Agent's execution process\"\"\"\n\n summary_msg = Message(role=\"user\", content=summary_prompt)\n response = await self.llm.generate(\n messages=[\n Message(\n role=\"system\",\n content=\"You are an assistant skilled at summarizing Agent execution processes.\",\n ),\n summary_msg,\n ]\n )\n\n summary_text = response.content\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary for round {round_num} generated successfully{Colors.RESET}\")\n return summary_text\n\n except Exception as e:\n print(f\"{Colors.BRIGHT_RED}✗ Summary generation failed for round {round_num}: {e}{Colors.RESET}\")\n # Use simple text summary on failure\n return summary_content\n\n async def run(self, cancel_event: Optional[asyncio.Event] = None) -> str:\n \"\"\"Execute agent loop until task is complete or max steps reached.\n\n Args:\n cancel_event: Optional asyncio.Event that can be set to cancel execution.\n When set, the agent will stop at the next safe checkpoint\n (after completing the current step to keep messages consistent).\n\n Returns:\n The final response content, or error message (including cancellation message).\n \"\"\"\n # Set cancellation event (can also be set via self.cancel_event before calling run())\n if cancel_event is not None:\n self.cancel_event = cancel_event\n\n # Start new run, initialize log file\n self.logger.start_new_run()\n print(f\"{Colors.DIM}📝 Log file: {self.logger.get_log_file_path()}{Colors.RESET}\")\n\n step = 0\n run_start_time = perf_counter()\n\n while step < self.max_steps:\n # Check for cancellation at start of each step\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_start_time = perf_counter()\n # Check and summarize message history to prevent context overflow\n await self._summarize_messages()\n\n # Step header with proper width calculation\n BOX_WIDTH = 58\n step_text = f\"{Colors.BOLD}{Colors.BRIGHT_CYAN}💭 Step {step + 1}/{self.max_steps}{Colors.RESET}\"\n step_display_width = calculate_display_width(step_text)\n padding = max(0, BOX_WIDTH - 1 - step_display_width) # -1 for leading space\n\n print(f\"\\n{Colors.DIM}╭{'─' * BOX_WIDTH}╮{Colors.RESET}\")\n print(f\"{Colors.DIM}│{Colors.RESET} {step_text}{' ' * padding}{Colors.DIM}│{Colors.RESET}\")\n print(f\"{Colors.DIM}╰{'─' * BOX_WIDTH}╯{Colors.RESET}\")\n\n # Get tool list for LLM call\n tool_list = list(self.tools.values())\n\n # Log LLM request and call LLM with Tool objects directly\n self.logger.log_request(messages=self.messages, tools=tool_list)\n\n try:\n response = await self.llm.generate(messages=self.messages, tools=tool_list)\n except Exception as e:\n # Check if it's a retry exhausted error\n from .retry import RetryExhaustedError\n\n if isinstance(e, RetryExhaustedError):\n error_msg = f\"LLM call failed after {e.attempts} retries\\nLast error: {str(e.last_exception)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Retry failed:{Colors.RESET} {error_msg}\")\n else:\n error_msg = f\"LLM call failed: {str(e)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Error:{Colors.RESET} {error_msg}\")\n return error_msg\n\n # Accumulate API reported token usage\n if response.usage:\n self.api_total_tokens = response.usage.total_tokens\n\n # Log LLM response\n self.logger.log_response(\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n finish_reason=response.finish_reason,\n )\n\n # Add assistant message\n assistant_msg = Message(\n role=\"assistant\",\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n )\n self.messages.append(assistant_msg)\n\n # Print thinking if present\n if response.thinking:\n print(f\"\\n{Colors.BOLD}{Colors.MAGENTA}🧠 Thinking:{Colors.RESET}\")\n print(f\"{Colors.DIM}{response.thinking}{Colors.RESET}\")\n\n # Print assistant response\n if response.content:\n print(f\"\\n{Colors.BOLD}{Colors.BRIGHT_BLUE}🤖 Assistant:{Colors.RESET}\")\n print(f\"{response.content}\")\n\n # Check if task is complete (no tool calls)\n if not response.tool_calls:\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n return response.content\n\n # Check for cancellation before executing tools\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n # Execute tool calls\n for tool_call in response.tool_calls:\n tool_call_id = tool_call.id\n function_name = tool_call.function.name\n arguments = tool_call.function.arguments\n\n # Tool call header\n print(f\"\\n{Colors.BRIGHT_YELLOW}🔧 Tool Call:{Colors.RESET} {Colors.BOLD}{Colors.CYAN}{function_name}{Colors.RESET}\")\n\n # Arguments (formatted display)\n print(f\"{Colors.DIM} Arguments:{Colors.RESET}\")\n # Truncate each argument value to avoid overly long output\n truncated_args = {}\n for key, value in arguments.items():\n value_str = str(value)\n if len(value_str) > 200:\n truncated_args[key] = value_str[:200] + \"...\"\n else:\n truncated_args[key] = value\n args_json = json.dumps(truncated_args, indent=2, ensure_ascii=False)\n for line in args_json.split(\"\\n\"):\n print(f\" {Colors.DIM}{line}{Colors.RESET}\")\n\n # Execute tool\n if function_name not in self.tools:\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Unknown tool: {function_name}\",\n )\n else:\n try:\n tool = self.tools[function_name]\n result = await tool.execute(**arguments)\n except Exception as e:\n # Catch all exceptions during tool execution, convert to failed ToolResult\n import traceback\n\n error_detail = f\"{type(e).__name__}: {str(e)}\"\n error_trace = traceback.format_exc()\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Tool execution failed: {error_detail}\\n\\nTraceback:\\n{error_trace}\",\n )\n\n # Log tool execution result\n self.logger.log_tool_result(\n tool_name=function_name,\n arguments=arguments,\n result_success=result.success,\n result_content=result.content if result.success else None,\n result_error=result.error if not result.success else None,\n )\n\n # Print result\n if result.success:\n result_text = result.content\n if len(result_text) > 300:\n result_text = result_text[:300] + f\"{Colors.DIM}...{Colors.RESET}\"\n print(f\"{Colors.BRIGHT_GREEN}✓ Result:{Colors.RESET} {result_text}\")\n else:\n print(f\"{Colors.BRIGHT_RED}✗ Error:{Colors.RESET} {Colors.RED}{result.error}{Colors.RESET}\")\n\n # Add tool result message\n tool_msg = Message(\n role=\"tool\",\n content=result.content if result.success else f\"Error: {result.error}\",\n tool_call_id=tool_call_id,\n name=function_name,\n )\n self.messages.append(tool_msg)\n\n # Check for cancellation after each tool execution\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n\n step += 1\n\n # Max steps reached\n error_msg = f\"Task couldn't be completed after {self.max_steps} steps.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {error_msg}{Colors.RESET}\")\n return error_msg\n\n def get_history(self) -> list[Message]:\n \"\"\"Get message history.\"\"\"\n return self.messages.copy()\n\n\n# Source: mini_agent/tools/file_tools.py\nclass ReadTool(Tool):\n \"\"\"Read file content.\"\"\"\n\n def __init__(self, workspace_dir: str = \".\"):\n \"\"\"Initialize ReadTool with workspace directory.\n\n Args:\n workspace_dir: Base directory for resolving relative paths\n \"\"\"\n self.workspace_dir = Path(workspace_dir).absolute()\n\n @property\n def name(self) -> str:\n return \"read_file\"\n\n @property\n def description(self) -> str:\n return (\n \"Read file contents from the filesystem. Output always includes line numbers \"\n \"in format 'LINE_NUMBER|LINE_CONTENT' (1-indexed). Supports reading partial content \"\n \"by specifying line offset and limit for large files. \"\n \"You can call this tool multiple times in parallel to read different files simultaneously.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"type\": \"string\",\n \"description\": \"Absolute or relative path to the file\",\n },\n \"offset\": {\n \"type\": \"integer\",\n \"description\": \"Starting line number (1-indexed). Use for large files to read from specific line\",\n },\n \"limit\": {\n \"type\": \"integer\",\n \"description\": \"Number of lines to read. Use with offset for large files to read in chunks\",\n },\n },\n \"required\": [\"path\"],\n }\n\n async def execute(self, path: str, offset: int | None = None, limit: int | None = None) -> ToolResult:\n \"\"\"Execute read file.\"\"\"\n try:\n file_path = Path(path)\n # Resolve relative paths relative to workspace_dir\n if not file_path.is_absolute():\n file_path = self.workspace_dir / file_path\n\n if not file_path.exists():\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"File not found: {path}\",\n )\n\n # Read file content with line numbers\n with open(file_path, encoding=\"utf-8\") as f:\n lines = f.readlines()\n\n # Apply offset and limit\n start = (offset - 1) if offset else 0\n end = (start + limit) if limit else len(lines)\n if start < 0:\n start = 0\n if end > len(lines):\n end = len(lines)\n\n selected_lines = lines[start:end]\n\n # Format with line numbers (1-indexed)\n numbered_lines = []\n for i, line in enumerate(selected_lines, start=start + 1):\n # Remove trailing newline for formatting\n line_content = line.rstrip(\"\\n\")\n numbered_lines.append(f\"{i:6d}|{line_content}\")\n\n content = \"\\n\".join(numbered_lines)\n\n # Apply token truncation if needed\n max_tokens = 32000\n content = truncate_text_by_tokens(content, max_tokens)\n\n return ToolResult(success=True, content=content)\n except Exception as e:\n return ToolResult(success=False, content=\"\", error=str(e))\n\nclass WriteTool(Tool):\n \"\"\"Write content to a file.\"\"\"\n\n def __init__(self, workspace_dir: str = \".\"):\n \"\"\"Initialize WriteTool with workspace directory.\n\n Args:\n workspace_dir: Base directory for resolving relative paths\n \"\"\"\n self.workspace_dir = Path(workspace_dir).absolute()\n\n @property\n def name(self) -> str:\n return \"write_file\"\n\n @property\n def description(self) -> str:\n return (\n \"Write content to a file. Will overwrite existing files completely. \"\n \"For existing files, you should read the file first using read_file. \"\n \"Prefer editing existing files over creating new ones unless explicitly needed.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"type\": \"string\",\n \"description\": \"Absolute or relative path to the file\",\n },\n \"content\": {\n \"type\": \"string\",\n \"description\": \"Complete content to write (will replace existing content)\",\n },\n },\n \"required\": [\"path\", \"content\"],\n }\n\n async def execute(self, path: str, content: str) -> ToolResult:\n \"\"\"Execute write file.\"\"\"\n try:\n file_path = Path(path)\n # Resolve relative paths relative to workspace_dir\n if not file_path.is_absolute():\n file_path = self.workspace_dir / file_path\n\n # Create parent directories if they don't exist\n file_path.parent.mkdir(parents=True, exist_ok=True)\n\n file_path.write_text(content, encoding=\"utf-8\")\n return ToolResult(success=True, content=f\"Successfully wrote to {file_path}\")\n except Exception as e:\n return ToolResult(success=False, content=\"\", error=str(e))\n\n\n# Source: mini_agent/tools/note_tool.py\nclass SessionNoteTool(Tool):\n \"\"\"Tool for recording and recalling session notes.\n\n The agent can use this tool to:\n - Record important facts, decisions, or context during sessions\n - Recall information from previous sessions\n - Build up knowledge over time\n\n Example usage by agent:\n - record_note(\"User prefers concise responses\")\n - record_note(\"Project uses Python 3.12 and async/await\")\n - recall_notes() -> retrieves all recorded notes\n \"\"\"\n\n def __init__(self, memory_file: str = \"./workspace/.agent_memory.json\"):\n \"\"\"Initialize session note tool.\n\n Args:\n memory_file: Path to the note storage file\n \"\"\"\n self.memory_file = Path(memory_file)\n # Lazy loading: file and directory are only created when first note is recorded\n\n @property\n def name(self) -> str:\n return \"record_note\"\n\n @property\n def description(self) -> str:\n return (\n \"Record important information as session notes for future reference. \"\n \"Use this to record key facts, user preferences, decisions, or context \"\n \"that should be recalled later in the agent execution chain. Each note is timestamped.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"content\": {\n \"type\": \"string\",\n \"description\": \"The information to record as a note. Be concise but specific.\",\n },\n \"category\": {\n \"type\": \"string\",\n \"description\": \"Optional category/tag for this note (e.g., 'user_preference', 'project_info', 'decision')\",\n },\n },\n \"required\": [\"content\"],\n }\n\n def _load_from_file(self) -> list:\n \"\"\"Load notes from file.\n \n Returns empty list if file doesn't exist (lazy loading).\n \"\"\"\n if not self.memory_file.exists():\n return []\n \n try:\n return json.loads(self.memory_file.read_text())\n except Exception:\n return []\n\n def _save_to_file(self, notes: list):\n \"\"\"Save notes to file.\n \n Creates parent directory and file if they don't exist (lazy initialization).\n \"\"\"\n # Ensure parent directory exists when actually saving\n self.memory_file.parent.mkdir(parents=True, exist_ok=True)\n self.memory_file.write_text(json.dumps(notes, indent=2, ensure_ascii=False))\n\n async def execute(self, content: str, category: str = \"general\") -> ToolResult:\n \"\"\"Record a session note.\n\n Args:\n content: The information to record\n category: Category/tag for this note\n\n Returns:\n ToolResult with success status\n \"\"\"\n try:\n # Load existing notes\n notes = self._load_from_file()\n\n # Add new note with timestamp\n note = {\n \"timestamp\": datetime.now().isoformat(),\n \"category\": category,\n \"content\": content,\n }\n notes.append(note)\n\n # Save back to file\n self._save_to_file(notes)\n\n return ToolResult(\n success=True,\n content=f\"Recorded note: {content} (category: {category})\",\n )\n except Exception as e:\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"Failed to record note: {str(e)}\",\n )", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 29731}, "tests/test_session_integration.py::97": {"resolved_imports": ["mini_agent/llm/__init__.py", "mini_agent/agent.py", "mini_agent/schema/schema.py", "mini_agent/tools/bash_tool.py", "mini_agent/tools/file_tools.py", "mini_agent/tools/note_tool.py"], "used_names": ["Agent"], "enclosing_function": "test_session_history_management", "extracted_code": "# Source: mini_agent/agent.py\nclass Agent:\n \"\"\"Single agent with basic tools and MCP support.\"\"\"\n\n def __init__(\n self,\n llm_client: LLMClient,\n system_prompt: str,\n tools: list[Tool],\n max_steps: int = 50,\n workspace_dir: str = \"./workspace\",\n token_limit: int = 80000, # Summary triggered when tokens exceed this value\n ):\n self.llm = llm_client\n self.tools = {tool.name: tool for tool in tools}\n self.max_steps = max_steps\n self.token_limit = token_limit\n self.workspace_dir = Path(workspace_dir)\n # Cancellation event for interrupting agent execution (set externally, e.g., by Esc key)\n self.cancel_event: Optional[asyncio.Event] = None\n\n # Ensure workspace exists\n self.workspace_dir.mkdir(parents=True, exist_ok=True)\n\n # Inject workspace information into system prompt if not already present\n if \"Current Workspace\" not in system_prompt:\n workspace_info = f\"\\n\\n## Current Workspace\\nYou are currently working in: `{self.workspace_dir.absolute()}`\\nAll relative paths will be resolved relative to this directory.\"\n system_prompt = system_prompt + workspace_info\n\n self.system_prompt = system_prompt\n\n # Initialize message history\n self.messages: list[Message] = [Message(role=\"system\", content=system_prompt)]\n\n # Initialize logger\n self.logger = AgentLogger()\n\n # Token usage from last API response (updated after each LLM call)\n self.api_total_tokens: int = 0\n # Flag to skip token check right after summary (avoid consecutive triggers)\n self._skip_next_token_check: bool = False\n\n def add_user_message(self, content: str):\n \"\"\"Add a user message to history.\"\"\"\n self.messages.append(Message(role=\"user\", content=content))\n\n def _check_cancelled(self) -> bool:\n \"\"\"Check if agent execution has been cancelled.\n\n Returns:\n True if cancelled, False otherwise.\n \"\"\"\n if self.cancel_event is not None and self.cancel_event.is_set():\n return True\n return False\n\n def _cleanup_incomplete_messages(self):\n \"\"\"Remove the incomplete assistant message and its partial tool results.\n\n This ensures message consistency after cancellation by removing\n only the current step's incomplete messages, preserving completed steps.\n \"\"\"\n # Find the index of the last assistant message\n last_assistant_idx = -1\n for i in range(len(self.messages) - 1, -1, -1):\n if self.messages[i].role == \"assistant\":\n last_assistant_idx = i\n break\n\n if last_assistant_idx == -1:\n # No assistant message found, nothing to clean\n return\n\n # Remove the last assistant message and all tool results after it\n removed_count = len(self.messages) - last_assistant_idx\n if removed_count > 0:\n self.messages = self.messages[:last_assistant_idx]\n print(f\"{Colors.DIM} Cleaned up {removed_count} incomplete message(s){Colors.RESET}\")\n\n def _estimate_tokens(self) -> int:\n \"\"\"Accurately calculate token count for message history using tiktoken\n\n Uses cl100k_base encoder (GPT-4/Claude/M2 compatible)\n \"\"\"\n try:\n # Use cl100k_base encoder (used by GPT-4 and most modern models)\n encoding = tiktoken.get_encoding(\"cl100k_base\")\n except Exception:\n # Fallback: if tiktoken initialization fails, use simple estimation\n return self._estimate_tokens_fallback()\n\n total_tokens = 0\n\n for msg in self.messages:\n # Count text content\n if isinstance(msg.content, str):\n total_tokens += len(encoding.encode(msg.content))\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n # Convert dict to string for calculation\n total_tokens += len(encoding.encode(str(block)))\n\n # Count thinking\n if msg.thinking:\n total_tokens += len(encoding.encode(msg.thinking))\n\n # Count tool_calls\n if msg.tool_calls:\n total_tokens += len(encoding.encode(str(msg.tool_calls)))\n\n # Metadata overhead per message (approximately 4 tokens)\n total_tokens += 4\n\n return total_tokens\n\n def _estimate_tokens_fallback(self) -> int:\n \"\"\"Fallback token estimation method (when tiktoken is unavailable)\"\"\"\n total_chars = 0\n for msg in self.messages:\n if isinstance(msg.content, str):\n total_chars += len(msg.content)\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n total_chars += len(str(block))\n\n if msg.thinking:\n total_chars += len(msg.thinking)\n\n if msg.tool_calls:\n total_chars += len(str(msg.tool_calls))\n\n # Rough estimation: average 2.5 characters = 1 token\n return int(total_chars / 2.5)\n\n async def _summarize_messages(self):\n \"\"\"Message history summarization: summarize conversations between user messages when tokens exceed limit\n\n Strategy (Agent mode):\n - Keep all user messages (these are user intents)\n - Summarize content between each user-user pair (agent execution process)\n - If last round is still executing (has agent/tool messages but no next user), also summarize\n - Structure: system -> user1 -> summary1 -> user2 -> summary2 -> user3 -> summary3 (if executing)\n\n Summary is triggered when EITHER:\n - Local token estimation exceeds limit\n - API reported total_tokens exceeds limit\n \"\"\"\n # Skip check if we just completed a summary (wait for next LLM call to update api_total_tokens)\n if self._skip_next_token_check:\n self._skip_next_token_check = False\n return\n\n estimated_tokens = self._estimate_tokens()\n\n # Check both local estimation and API reported tokens\n should_summarize = estimated_tokens > self.token_limit or self.api_total_tokens > self.token_limit\n\n # If neither exceeded, no summary needed\n if not should_summarize:\n return\n\n print(\n f\"\\n{Colors.BRIGHT_YELLOW}📊 Token usage - Local estimate: {estimated_tokens}, API reported: {self.api_total_tokens}, Limit: {self.token_limit}{Colors.RESET}\"\n )\n print(f\"{Colors.BRIGHT_YELLOW}🔄 Triggering message history summarization...{Colors.RESET}\")\n\n # Find all user message indices (skip system prompt)\n user_indices = [i for i, msg in enumerate(self.messages) if msg.role == \"user\" and i > 0]\n\n # Need at least 1 user message to perform summary\n if len(user_indices) < 1:\n print(f\"{Colors.BRIGHT_YELLOW}⚠️ Insufficient messages, cannot summarize{Colors.RESET}\")\n return\n\n # Build new message list\n new_messages = [self.messages[0]] # Keep system prompt\n summary_count = 0\n\n # Iterate through each user message and summarize the execution process after it\n for i, user_idx in enumerate(user_indices):\n # Add current user message\n new_messages.append(self.messages[user_idx])\n\n # Determine message range to summarize\n # If last user, go to end of message list; otherwise to before next user\n if i < len(user_indices) - 1:\n next_user_idx = user_indices[i + 1]\n else:\n next_user_idx = len(self.messages)\n\n # Extract execution messages for this round\n execution_messages = self.messages[user_idx + 1 : next_user_idx]\n\n # If there are execution messages in this round, summarize them\n if execution_messages:\n summary_text = await self._create_summary(execution_messages, i + 1)\n if summary_text:\n summary_message = Message(\n role=\"user\",\n content=f\"[Assistant Execution Summary]\\n\\n{summary_text}\",\n )\n new_messages.append(summary_message)\n summary_count += 1\n\n # Replace message list\n self.messages = new_messages\n\n # Skip next token check to avoid consecutive summary triggers\n # (api_total_tokens will be updated after next LLM call)\n self._skip_next_token_check = True\n\n new_tokens = self._estimate_tokens()\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary completed, local tokens: {estimated_tokens} → {new_tokens}{Colors.RESET}\")\n print(f\"{Colors.DIM} Structure: system + {len(user_indices)} user messages + {summary_count} summaries{Colors.RESET}\")\n print(f\"{Colors.DIM} Note: API token count will update on next LLM call{Colors.RESET}\")\n\n async def _create_summary(self, messages: list[Message], round_num: int) -> str:\n \"\"\"Create summary for one execution round\n\n Args:\n messages: List of messages to summarize\n round_num: Round number\n\n Returns:\n Summary text\n \"\"\"\n if not messages:\n return \"\"\n\n # Build summary content\n summary_content = f\"Round {round_num} execution process:\\n\\n\"\n for msg in messages:\n if msg.role == \"assistant\":\n content_text = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\"Assistant: {content_text}\\n\"\n if msg.tool_calls:\n tool_names = [tc.function.name for tc in msg.tool_calls]\n summary_content += f\" → Called tools: {', '.join(tool_names)}\\n\"\n elif msg.role == \"tool\":\n result_preview = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\" ← Tool returned: {result_preview}...\\n\"\n\n # Call LLM to generate concise summary\n try:\n summary_prompt = f\"\"\"Please provide a concise summary of the following Agent execution process:\n\n{summary_content}\n\nRequirements:\n1. Focus on what tasks were completed and which tools were called\n2. Keep key execution results and important findings\n3. Be concise and clear, within 1000 words\n4. Use English\n5. Do not include \"user\" related content, only summarize the Agent's execution process\"\"\"\n\n summary_msg = Message(role=\"user\", content=summary_prompt)\n response = await self.llm.generate(\n messages=[\n Message(\n role=\"system\",\n content=\"You are an assistant skilled at summarizing Agent execution processes.\",\n ),\n summary_msg,\n ]\n )\n\n summary_text = response.content\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary for round {round_num} generated successfully{Colors.RESET}\")\n return summary_text\n\n except Exception as e:\n print(f\"{Colors.BRIGHT_RED}✗ Summary generation failed for round {round_num}: {e}{Colors.RESET}\")\n # Use simple text summary on failure\n return summary_content\n\n async def run(self, cancel_event: Optional[asyncio.Event] = None) -> str:\n \"\"\"Execute agent loop until task is complete or max steps reached.\n\n Args:\n cancel_event: Optional asyncio.Event that can be set to cancel execution.\n When set, the agent will stop at the next safe checkpoint\n (after completing the current step to keep messages consistent).\n\n Returns:\n The final response content, or error message (including cancellation message).\n \"\"\"\n # Set cancellation event (can also be set via self.cancel_event before calling run())\n if cancel_event is not None:\n self.cancel_event = cancel_event\n\n # Start new run, initialize log file\n self.logger.start_new_run()\n print(f\"{Colors.DIM}📝 Log file: {self.logger.get_log_file_path()}{Colors.RESET}\")\n\n step = 0\n run_start_time = perf_counter()\n\n while step < self.max_steps:\n # Check for cancellation at start of each step\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_start_time = perf_counter()\n # Check and summarize message history to prevent context overflow\n await self._summarize_messages()\n\n # Step header with proper width calculation\n BOX_WIDTH = 58\n step_text = f\"{Colors.BOLD}{Colors.BRIGHT_CYAN}💭 Step {step + 1}/{self.max_steps}{Colors.RESET}\"\n step_display_width = calculate_display_width(step_text)\n padding = max(0, BOX_WIDTH - 1 - step_display_width) # -1 for leading space\n\n print(f\"\\n{Colors.DIM}╭{'─' * BOX_WIDTH}╮{Colors.RESET}\")\n print(f\"{Colors.DIM}│{Colors.RESET} {step_text}{' ' * padding}{Colors.DIM}│{Colors.RESET}\")\n print(f\"{Colors.DIM}╰{'─' * BOX_WIDTH}╯{Colors.RESET}\")\n\n # Get tool list for LLM call\n tool_list = list(self.tools.values())\n\n # Log LLM request and call LLM with Tool objects directly\n self.logger.log_request(messages=self.messages, tools=tool_list)\n\n try:\n response = await self.llm.generate(messages=self.messages, tools=tool_list)\n except Exception as e:\n # Check if it's a retry exhausted error\n from .retry import RetryExhaustedError\n\n if isinstance(e, RetryExhaustedError):\n error_msg = f\"LLM call failed after {e.attempts} retries\\nLast error: {str(e.last_exception)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Retry failed:{Colors.RESET} {error_msg}\")\n else:\n error_msg = f\"LLM call failed: {str(e)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Error:{Colors.RESET} {error_msg}\")\n return error_msg\n\n # Accumulate API reported token usage\n if response.usage:\n self.api_total_tokens = response.usage.total_tokens\n\n # Log LLM response\n self.logger.log_response(\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n finish_reason=response.finish_reason,\n )\n\n # Add assistant message\n assistant_msg = Message(\n role=\"assistant\",\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n )\n self.messages.append(assistant_msg)\n\n # Print thinking if present\n if response.thinking:\n print(f\"\\n{Colors.BOLD}{Colors.MAGENTA}🧠 Thinking:{Colors.RESET}\")\n print(f\"{Colors.DIM}{response.thinking}{Colors.RESET}\")\n\n # Print assistant response\n if response.content:\n print(f\"\\n{Colors.BOLD}{Colors.BRIGHT_BLUE}🤖 Assistant:{Colors.RESET}\")\n print(f\"{response.content}\")\n\n # Check if task is complete (no tool calls)\n if not response.tool_calls:\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n return response.content\n\n # Check for cancellation before executing tools\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n # Execute tool calls\n for tool_call in response.tool_calls:\n tool_call_id = tool_call.id\n function_name = tool_call.function.name\n arguments = tool_call.function.arguments\n\n # Tool call header\n print(f\"\\n{Colors.BRIGHT_YELLOW}🔧 Tool Call:{Colors.RESET} {Colors.BOLD}{Colors.CYAN}{function_name}{Colors.RESET}\")\n\n # Arguments (formatted display)\n print(f\"{Colors.DIM} Arguments:{Colors.RESET}\")\n # Truncate each argument value to avoid overly long output\n truncated_args = {}\n for key, value in arguments.items():\n value_str = str(value)\n if len(value_str) > 200:\n truncated_args[key] = value_str[:200] + \"...\"\n else:\n truncated_args[key] = value\n args_json = json.dumps(truncated_args, indent=2, ensure_ascii=False)\n for line in args_json.split(\"\\n\"):\n print(f\" {Colors.DIM}{line}{Colors.RESET}\")\n\n # Execute tool\n if function_name not in self.tools:\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Unknown tool: {function_name}\",\n )\n else:\n try:\n tool = self.tools[function_name]\n result = await tool.execute(**arguments)\n except Exception as e:\n # Catch all exceptions during tool execution, convert to failed ToolResult\n import traceback\n\n error_detail = f\"{type(e).__name__}: {str(e)}\"\n error_trace = traceback.format_exc()\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Tool execution failed: {error_detail}\\n\\nTraceback:\\n{error_trace}\",\n )\n\n # Log tool execution result\n self.logger.log_tool_result(\n tool_name=function_name,\n arguments=arguments,\n result_success=result.success,\n result_content=result.content if result.success else None,\n result_error=result.error if not result.success else None,\n )\n\n # Print result\n if result.success:\n result_text = result.content\n if len(result_text) > 300:\n result_text = result_text[:300] + f\"{Colors.DIM}...{Colors.RESET}\"\n print(f\"{Colors.BRIGHT_GREEN}✓ Result:{Colors.RESET} {result_text}\")\n else:\n print(f\"{Colors.BRIGHT_RED}✗ Error:{Colors.RESET} {Colors.RED}{result.error}{Colors.RESET}\")\n\n # Add tool result message\n tool_msg = Message(\n role=\"tool\",\n content=result.content if result.success else f\"Error: {result.error}\",\n tool_call_id=tool_call_id,\n name=function_name,\n )\n self.messages.append(tool_msg)\n\n # Check for cancellation after each tool execution\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n\n step += 1\n\n # Max steps reached\n error_msg = f\"Task couldn't be completed after {self.max_steps} steps.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {error_msg}{Colors.RESET}\")\n return error_msg\n\n def get_history(self) -> list[Message]:\n \"\"\"Get message history.\"\"\"\n return self.messages.copy()", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 20770}, "tests/test_session_integration.py::117": {"resolved_imports": ["mini_agent/llm/__init__.py", "mini_agent/agent.py", "mini_agent/schema/schema.py", "mini_agent/tools/bash_tool.py", "mini_agent/tools/file_tools.py", "mini_agent/tools/note_tool.py"], "used_names": ["Agent", "Message"], "enclosing_function": "test_get_history", "extracted_code": "# Source: mini_agent/agent.py\nclass Agent:\n \"\"\"Single agent with basic tools and MCP support.\"\"\"\n\n def __init__(\n self,\n llm_client: LLMClient,\n system_prompt: str,\n tools: list[Tool],\n max_steps: int = 50,\n workspace_dir: str = \"./workspace\",\n token_limit: int = 80000, # Summary triggered when tokens exceed this value\n ):\n self.llm = llm_client\n self.tools = {tool.name: tool for tool in tools}\n self.max_steps = max_steps\n self.token_limit = token_limit\n self.workspace_dir = Path(workspace_dir)\n # Cancellation event for interrupting agent execution (set externally, e.g., by Esc key)\n self.cancel_event: Optional[asyncio.Event] = None\n\n # Ensure workspace exists\n self.workspace_dir.mkdir(parents=True, exist_ok=True)\n\n # Inject workspace information into system prompt if not already present\n if \"Current Workspace\" not in system_prompt:\n workspace_info = f\"\\n\\n## Current Workspace\\nYou are currently working in: `{self.workspace_dir.absolute()}`\\nAll relative paths will be resolved relative to this directory.\"\n system_prompt = system_prompt + workspace_info\n\n self.system_prompt = system_prompt\n\n # Initialize message history\n self.messages: list[Message] = [Message(role=\"system\", content=system_prompt)]\n\n # Initialize logger\n self.logger = AgentLogger()\n\n # Token usage from last API response (updated after each LLM call)\n self.api_total_tokens: int = 0\n # Flag to skip token check right after summary (avoid consecutive triggers)\n self._skip_next_token_check: bool = False\n\n def add_user_message(self, content: str):\n \"\"\"Add a user message to history.\"\"\"\n self.messages.append(Message(role=\"user\", content=content))\n\n def _check_cancelled(self) -> bool:\n \"\"\"Check if agent execution has been cancelled.\n\n Returns:\n True if cancelled, False otherwise.\n \"\"\"\n if self.cancel_event is not None and self.cancel_event.is_set():\n return True\n return False\n\n def _cleanup_incomplete_messages(self):\n \"\"\"Remove the incomplete assistant message and its partial tool results.\n\n This ensures message consistency after cancellation by removing\n only the current step's incomplete messages, preserving completed steps.\n \"\"\"\n # Find the index of the last assistant message\n last_assistant_idx = -1\n for i in range(len(self.messages) - 1, -1, -1):\n if self.messages[i].role == \"assistant\":\n last_assistant_idx = i\n break\n\n if last_assistant_idx == -1:\n # No assistant message found, nothing to clean\n return\n\n # Remove the last assistant message and all tool results after it\n removed_count = len(self.messages) - last_assistant_idx\n if removed_count > 0:\n self.messages = self.messages[:last_assistant_idx]\n print(f\"{Colors.DIM} Cleaned up {removed_count} incomplete message(s){Colors.RESET}\")\n\n def _estimate_tokens(self) -> int:\n \"\"\"Accurately calculate token count for message history using tiktoken\n\n Uses cl100k_base encoder (GPT-4/Claude/M2 compatible)\n \"\"\"\n try:\n # Use cl100k_base encoder (used by GPT-4 and most modern models)\n encoding = tiktoken.get_encoding(\"cl100k_base\")\n except Exception:\n # Fallback: if tiktoken initialization fails, use simple estimation\n return self._estimate_tokens_fallback()\n\n total_tokens = 0\n\n for msg in self.messages:\n # Count text content\n if isinstance(msg.content, str):\n total_tokens += len(encoding.encode(msg.content))\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n # Convert dict to string for calculation\n total_tokens += len(encoding.encode(str(block)))\n\n # Count thinking\n if msg.thinking:\n total_tokens += len(encoding.encode(msg.thinking))\n\n # Count tool_calls\n if msg.tool_calls:\n total_tokens += len(encoding.encode(str(msg.tool_calls)))\n\n # Metadata overhead per message (approximately 4 tokens)\n total_tokens += 4\n\n return total_tokens\n\n def _estimate_tokens_fallback(self) -> int:\n \"\"\"Fallback token estimation method (when tiktoken is unavailable)\"\"\"\n total_chars = 0\n for msg in self.messages:\n if isinstance(msg.content, str):\n total_chars += len(msg.content)\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n total_chars += len(str(block))\n\n if msg.thinking:\n total_chars += len(msg.thinking)\n\n if msg.tool_calls:\n total_chars += len(str(msg.tool_calls))\n\n # Rough estimation: average 2.5 characters = 1 token\n return int(total_chars / 2.5)\n\n async def _summarize_messages(self):\n \"\"\"Message history summarization: summarize conversations between user messages when tokens exceed limit\n\n Strategy (Agent mode):\n - Keep all user messages (these are user intents)\n - Summarize content between each user-user pair (agent execution process)\n - If last round is still executing (has agent/tool messages but no next user), also summarize\n - Structure: system -> user1 -> summary1 -> user2 -> summary2 -> user3 -> summary3 (if executing)\n\n Summary is triggered when EITHER:\n - Local token estimation exceeds limit\n - API reported total_tokens exceeds limit\n \"\"\"\n # Skip check if we just completed a summary (wait for next LLM call to update api_total_tokens)\n if self._skip_next_token_check:\n self._skip_next_token_check = False\n return\n\n estimated_tokens = self._estimate_tokens()\n\n # Check both local estimation and API reported tokens\n should_summarize = estimated_tokens > self.token_limit or self.api_total_tokens > self.token_limit\n\n # If neither exceeded, no summary needed\n if not should_summarize:\n return\n\n print(\n f\"\\n{Colors.BRIGHT_YELLOW}📊 Token usage - Local estimate: {estimated_tokens}, API reported: {self.api_total_tokens}, Limit: {self.token_limit}{Colors.RESET}\"\n )\n print(f\"{Colors.BRIGHT_YELLOW}🔄 Triggering message history summarization...{Colors.RESET}\")\n\n # Find all user message indices (skip system prompt)\n user_indices = [i for i, msg in enumerate(self.messages) if msg.role == \"user\" and i > 0]\n\n # Need at least 1 user message to perform summary\n if len(user_indices) < 1:\n print(f\"{Colors.BRIGHT_YELLOW}⚠️ Insufficient messages, cannot summarize{Colors.RESET}\")\n return\n\n # Build new message list\n new_messages = [self.messages[0]] # Keep system prompt\n summary_count = 0\n\n # Iterate through each user message and summarize the execution process after it\n for i, user_idx in enumerate(user_indices):\n # Add current user message\n new_messages.append(self.messages[user_idx])\n\n # Determine message range to summarize\n # If last user, go to end of message list; otherwise to before next user\n if i < len(user_indices) - 1:\n next_user_idx = user_indices[i + 1]\n else:\n next_user_idx = len(self.messages)\n\n # Extract execution messages for this round\n execution_messages = self.messages[user_idx + 1 : next_user_idx]\n\n # If there are execution messages in this round, summarize them\n if execution_messages:\n summary_text = await self._create_summary(execution_messages, i + 1)\n if summary_text:\n summary_message = Message(\n role=\"user\",\n content=f\"[Assistant Execution Summary]\\n\\n{summary_text}\",\n )\n new_messages.append(summary_message)\n summary_count += 1\n\n # Replace message list\n self.messages = new_messages\n\n # Skip next token check to avoid consecutive summary triggers\n # (api_total_tokens will be updated after next LLM call)\n self._skip_next_token_check = True\n\n new_tokens = self._estimate_tokens()\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary completed, local tokens: {estimated_tokens} → {new_tokens}{Colors.RESET}\")\n print(f\"{Colors.DIM} Structure: system + {len(user_indices)} user messages + {summary_count} summaries{Colors.RESET}\")\n print(f\"{Colors.DIM} Note: API token count will update on next LLM call{Colors.RESET}\")\n\n async def _create_summary(self, messages: list[Message], round_num: int) -> str:\n \"\"\"Create summary for one execution round\n\n Args:\n messages: List of messages to summarize\n round_num: Round number\n\n Returns:\n Summary text\n \"\"\"\n if not messages:\n return \"\"\n\n # Build summary content\n summary_content = f\"Round {round_num} execution process:\\n\\n\"\n for msg in messages:\n if msg.role == \"assistant\":\n content_text = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\"Assistant: {content_text}\\n\"\n if msg.tool_calls:\n tool_names = [tc.function.name for tc in msg.tool_calls]\n summary_content += f\" → Called tools: {', '.join(tool_names)}\\n\"\n elif msg.role == \"tool\":\n result_preview = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\" ← Tool returned: {result_preview}...\\n\"\n\n # Call LLM to generate concise summary\n try:\n summary_prompt = f\"\"\"Please provide a concise summary of the following Agent execution process:\n\n{summary_content}\n\nRequirements:\n1. Focus on what tasks were completed and which tools were called\n2. Keep key execution results and important findings\n3. Be concise and clear, within 1000 words\n4. Use English\n5. Do not include \"user\" related content, only summarize the Agent's execution process\"\"\"\n\n summary_msg = Message(role=\"user\", content=summary_prompt)\n response = await self.llm.generate(\n messages=[\n Message(\n role=\"system\",\n content=\"You are an assistant skilled at summarizing Agent execution processes.\",\n ),\n summary_msg,\n ]\n )\n\n summary_text = response.content\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary for round {round_num} generated successfully{Colors.RESET}\")\n return summary_text\n\n except Exception as e:\n print(f\"{Colors.BRIGHT_RED}✗ Summary generation failed for round {round_num}: {e}{Colors.RESET}\")\n # Use simple text summary on failure\n return summary_content\n\n async def run(self, cancel_event: Optional[asyncio.Event] = None) -> str:\n \"\"\"Execute agent loop until task is complete or max steps reached.\n\n Args:\n cancel_event: Optional asyncio.Event that can be set to cancel execution.\n When set, the agent will stop at the next safe checkpoint\n (after completing the current step to keep messages consistent).\n\n Returns:\n The final response content, or error message (including cancellation message).\n \"\"\"\n # Set cancellation event (can also be set via self.cancel_event before calling run())\n if cancel_event is not None:\n self.cancel_event = cancel_event\n\n # Start new run, initialize log file\n self.logger.start_new_run()\n print(f\"{Colors.DIM}📝 Log file: {self.logger.get_log_file_path()}{Colors.RESET}\")\n\n step = 0\n run_start_time = perf_counter()\n\n while step < self.max_steps:\n # Check for cancellation at start of each step\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_start_time = perf_counter()\n # Check and summarize message history to prevent context overflow\n await self._summarize_messages()\n\n # Step header with proper width calculation\n BOX_WIDTH = 58\n step_text = f\"{Colors.BOLD}{Colors.BRIGHT_CYAN}💭 Step {step + 1}/{self.max_steps}{Colors.RESET}\"\n step_display_width = calculate_display_width(step_text)\n padding = max(0, BOX_WIDTH - 1 - step_display_width) # -1 for leading space\n\n print(f\"\\n{Colors.DIM}╭{'─' * BOX_WIDTH}╮{Colors.RESET}\")\n print(f\"{Colors.DIM}│{Colors.RESET} {step_text}{' ' * padding}{Colors.DIM}│{Colors.RESET}\")\n print(f\"{Colors.DIM}╰{'─' * BOX_WIDTH}╯{Colors.RESET}\")\n\n # Get tool list for LLM call\n tool_list = list(self.tools.values())\n\n # Log LLM request and call LLM with Tool objects directly\n self.logger.log_request(messages=self.messages, tools=tool_list)\n\n try:\n response = await self.llm.generate(messages=self.messages, tools=tool_list)\n except Exception as e:\n # Check if it's a retry exhausted error\n from .retry import RetryExhaustedError\n\n if isinstance(e, RetryExhaustedError):\n error_msg = f\"LLM call failed after {e.attempts} retries\\nLast error: {str(e.last_exception)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Retry failed:{Colors.RESET} {error_msg}\")\n else:\n error_msg = f\"LLM call failed: {str(e)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Error:{Colors.RESET} {error_msg}\")\n return error_msg\n\n # Accumulate API reported token usage\n if response.usage:\n self.api_total_tokens = response.usage.total_tokens\n\n # Log LLM response\n self.logger.log_response(\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n finish_reason=response.finish_reason,\n )\n\n # Add assistant message\n assistant_msg = Message(\n role=\"assistant\",\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n )\n self.messages.append(assistant_msg)\n\n # Print thinking if present\n if response.thinking:\n print(f\"\\n{Colors.BOLD}{Colors.MAGENTA}🧠 Thinking:{Colors.RESET}\")\n print(f\"{Colors.DIM}{response.thinking}{Colors.RESET}\")\n\n # Print assistant response\n if response.content:\n print(f\"\\n{Colors.BOLD}{Colors.BRIGHT_BLUE}🤖 Assistant:{Colors.RESET}\")\n print(f\"{response.content}\")\n\n # Check if task is complete (no tool calls)\n if not response.tool_calls:\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n return response.content\n\n # Check for cancellation before executing tools\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n # Execute tool calls\n for tool_call in response.tool_calls:\n tool_call_id = tool_call.id\n function_name = tool_call.function.name\n arguments = tool_call.function.arguments\n\n # Tool call header\n print(f\"\\n{Colors.BRIGHT_YELLOW}🔧 Tool Call:{Colors.RESET} {Colors.BOLD}{Colors.CYAN}{function_name}{Colors.RESET}\")\n\n # Arguments (formatted display)\n print(f\"{Colors.DIM} Arguments:{Colors.RESET}\")\n # Truncate each argument value to avoid overly long output\n truncated_args = {}\n for key, value in arguments.items():\n value_str = str(value)\n if len(value_str) > 200:\n truncated_args[key] = value_str[:200] + \"...\"\n else:\n truncated_args[key] = value\n args_json = json.dumps(truncated_args, indent=2, ensure_ascii=False)\n for line in args_json.split(\"\\n\"):\n print(f\" {Colors.DIM}{line}{Colors.RESET}\")\n\n # Execute tool\n if function_name not in self.tools:\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Unknown tool: {function_name}\",\n )\n else:\n try:\n tool = self.tools[function_name]\n result = await tool.execute(**arguments)\n except Exception as e:\n # Catch all exceptions during tool execution, convert to failed ToolResult\n import traceback\n\n error_detail = f\"{type(e).__name__}: {str(e)}\"\n error_trace = traceback.format_exc()\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Tool execution failed: {error_detail}\\n\\nTraceback:\\n{error_trace}\",\n )\n\n # Log tool execution result\n self.logger.log_tool_result(\n tool_name=function_name,\n arguments=arguments,\n result_success=result.success,\n result_content=result.content if result.success else None,\n result_error=result.error if not result.success else None,\n )\n\n # Print result\n if result.success:\n result_text = result.content\n if len(result_text) > 300:\n result_text = result_text[:300] + f\"{Colors.DIM}...{Colors.RESET}\"\n print(f\"{Colors.BRIGHT_GREEN}✓ Result:{Colors.RESET} {result_text}\")\n else:\n print(f\"{Colors.BRIGHT_RED}✗ Error:{Colors.RESET} {Colors.RED}{result.error}{Colors.RESET}\")\n\n # Add tool result message\n tool_msg = Message(\n role=\"tool\",\n content=result.content if result.success else f\"Error: {result.error}\",\n tool_call_id=tool_call_id,\n name=function_name,\n )\n self.messages.append(tool_msg)\n\n # Check for cancellation after each tool execution\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n\n step += 1\n\n # Max steps reached\n error_msg = f\"Task couldn't be completed after {self.max_steps} steps.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {error_msg}{Colors.RESET}\")\n return error_msg\n\n def get_history(self) -> list[Message]:\n \"\"\"Get message history.\"\"\"\n return self.messages.copy()\n\n\n# Source: mini_agent/schema/schema.py\nclass Message(BaseModel):\n \"\"\"Chat message.\"\"\"\n\n role: str # \"system\", \"user\", \"assistant\", \"tool\"\n content: str | list[dict[str, Any]] # Can be string or list of content blocks\n thinking: str | None = None # Extended thinking content for assistant messages\n tool_calls: list[ToolCall] | None = None\n tool_call_id: str | None = None\n name: str | None = None", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 21192}, "tests/test_session_integration.py::141": {"resolved_imports": ["mini_agent/llm/__init__.py", "mini_agent/agent.py", "mini_agent/schema/schema.py", "mini_agent/tools/bash_tool.py", "mini_agent/tools/file_tools.py", "mini_agent/tools/note_tool.py"], "used_names": ["Path", "RecallNoteTool", "SessionNoteTool", "pytest"], "enclosing_function": "test_session_note_persistence", "extracted_code": "# Source: mini_agent/tools/note_tool.py\nclass SessionNoteTool(Tool):\n \"\"\"Tool for recording and recalling session notes.\n\n The agent can use this tool to:\n - Record important facts, decisions, or context during sessions\n - Recall information from previous sessions\n - Build up knowledge over time\n\n Example usage by agent:\n - record_note(\"User prefers concise responses\")\n - record_note(\"Project uses Python 3.12 and async/await\")\n - recall_notes() -> retrieves all recorded notes\n \"\"\"\n\n def __init__(self, memory_file: str = \"./workspace/.agent_memory.json\"):\n \"\"\"Initialize session note tool.\n\n Args:\n memory_file: Path to the note storage file\n \"\"\"\n self.memory_file = Path(memory_file)\n # Lazy loading: file and directory are only created when first note is recorded\n\n @property\n def name(self) -> str:\n return \"record_note\"\n\n @property\n def description(self) -> str:\n return (\n \"Record important information as session notes for future reference. \"\n \"Use this to record key facts, user preferences, decisions, or context \"\n \"that should be recalled later in the agent execution chain. Each note is timestamped.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"content\": {\n \"type\": \"string\",\n \"description\": \"The information to record as a note. Be concise but specific.\",\n },\n \"category\": {\n \"type\": \"string\",\n \"description\": \"Optional category/tag for this note (e.g., 'user_preference', 'project_info', 'decision')\",\n },\n },\n \"required\": [\"content\"],\n }\n\n def _load_from_file(self) -> list:\n \"\"\"Load notes from file.\n \n Returns empty list if file doesn't exist (lazy loading).\n \"\"\"\n if not self.memory_file.exists():\n return []\n \n try:\n return json.loads(self.memory_file.read_text())\n except Exception:\n return []\n\n def _save_to_file(self, notes: list):\n \"\"\"Save notes to file.\n \n Creates parent directory and file if they don't exist (lazy initialization).\n \"\"\"\n # Ensure parent directory exists when actually saving\n self.memory_file.parent.mkdir(parents=True, exist_ok=True)\n self.memory_file.write_text(json.dumps(notes, indent=2, ensure_ascii=False))\n\n async def execute(self, content: str, category: str = \"general\") -> ToolResult:\n \"\"\"Record a session note.\n\n Args:\n content: The information to record\n category: Category/tag for this note\n\n Returns:\n ToolResult with success status\n \"\"\"\n try:\n # Load existing notes\n notes = self._load_from_file()\n\n # Add new note with timestamp\n note = {\n \"timestamp\": datetime.now().isoformat(),\n \"category\": category,\n \"content\": content,\n }\n notes.append(note)\n\n # Save back to file\n self._save_to_file(notes)\n\n return ToolResult(\n success=True,\n content=f\"Recorded note: {content} (category: {category})\",\n )\n except Exception as e:\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"Failed to record note: {str(e)}\",\n )\n\nclass RecallNoteTool(Tool):\n \"\"\"Tool for recalling recorded session notes.\"\"\"\n\n def __init__(self, memory_file: str = \"./workspace/.agent_memory.json\"):\n \"\"\"Initialize recall note tool.\n\n Args:\n memory_file: Path to the note storage file\n \"\"\"\n self.memory_file = Path(memory_file)\n\n @property\n def name(self) -> str:\n return \"recall_notes\"\n\n @property\n def description(self) -> str:\n return (\n \"Recall all previously recorded session notes. \"\n \"Use this to retrieve important information, context, or decisions \"\n \"from earlier in the session or previous agent execution chains.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"category\": {\n \"type\": \"string\",\n \"description\": \"Optional: filter notes by category\",\n },\n },\n }\n\n async def execute(self, category: str = None) -> ToolResult:\n \"\"\"Recall session notes.\n\n Args:\n category: Optional category filter\n\n Returns:\n ToolResult with notes content\n \"\"\"\n try:\n if not self.memory_file.exists():\n return ToolResult(\n success=True,\n content=\"No notes recorded yet.\",\n )\n\n notes = json.loads(self.memory_file.read_text())\n\n if not notes:\n return ToolResult(\n success=True,\n content=\"No notes recorded yet.\",\n )\n\n # Filter by category if specified\n if category:\n notes = [n for n in notes if n.get(\"category\") == category]\n if not notes:\n return ToolResult(\n success=True,\n content=f\"No notes found in category: {category}\",\n )\n\n # Format notes for display\n formatted = []\n for idx, note in enumerate(notes, 1):\n timestamp = note.get(\"timestamp\", \"unknown time\")\n cat = note.get(\"category\", \"general\")\n content = note.get(\"content\", \"\")\n formatted.append(f\"{idx}. [{cat}] {content}\\n (recorded at {timestamp})\")\n\n result = \"Recorded Notes:\\n\" + \"\\n\".join(formatted)\n\n return ToolResult(success=True, content=result)\n\n except Exception as e:\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"Failed to recall notes: {str(e)}\",\n )", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 6386}, "tests/test_session_integration.py::116": {"resolved_imports": ["mini_agent/llm/__init__.py", "mini_agent/agent.py", "mini_agent/schema/schema.py", "mini_agent/tools/bash_tool.py", "mini_agent/tools/file_tools.py", "mini_agent/tools/note_tool.py"], "used_names": ["Agent", "Message"], "enclosing_function": "test_get_history", "extracted_code": "# Source: mini_agent/agent.py\nclass Agent:\n \"\"\"Single agent with basic tools and MCP support.\"\"\"\n\n def __init__(\n self,\n llm_client: LLMClient,\n system_prompt: str,\n tools: list[Tool],\n max_steps: int = 50,\n workspace_dir: str = \"./workspace\",\n token_limit: int = 80000, # Summary triggered when tokens exceed this value\n ):\n self.llm = llm_client\n self.tools = {tool.name: tool for tool in tools}\n self.max_steps = max_steps\n self.token_limit = token_limit\n self.workspace_dir = Path(workspace_dir)\n # Cancellation event for interrupting agent execution (set externally, e.g., by Esc key)\n self.cancel_event: Optional[asyncio.Event] = None\n\n # Ensure workspace exists\n self.workspace_dir.mkdir(parents=True, exist_ok=True)\n\n # Inject workspace information into system prompt if not already present\n if \"Current Workspace\" not in system_prompt:\n workspace_info = f\"\\n\\n## Current Workspace\\nYou are currently working in: `{self.workspace_dir.absolute()}`\\nAll relative paths will be resolved relative to this directory.\"\n system_prompt = system_prompt + workspace_info\n\n self.system_prompt = system_prompt\n\n # Initialize message history\n self.messages: list[Message] = [Message(role=\"system\", content=system_prompt)]\n\n # Initialize logger\n self.logger = AgentLogger()\n\n # Token usage from last API response (updated after each LLM call)\n self.api_total_tokens: int = 0\n # Flag to skip token check right after summary (avoid consecutive triggers)\n self._skip_next_token_check: bool = False\n\n def add_user_message(self, content: str):\n \"\"\"Add a user message to history.\"\"\"\n self.messages.append(Message(role=\"user\", content=content))\n\n def _check_cancelled(self) -> bool:\n \"\"\"Check if agent execution has been cancelled.\n\n Returns:\n True if cancelled, False otherwise.\n \"\"\"\n if self.cancel_event is not None and self.cancel_event.is_set():\n return True\n return False\n\n def _cleanup_incomplete_messages(self):\n \"\"\"Remove the incomplete assistant message and its partial tool results.\n\n This ensures message consistency after cancellation by removing\n only the current step's incomplete messages, preserving completed steps.\n \"\"\"\n # Find the index of the last assistant message\n last_assistant_idx = -1\n for i in range(len(self.messages) - 1, -1, -1):\n if self.messages[i].role == \"assistant\":\n last_assistant_idx = i\n break\n\n if last_assistant_idx == -1:\n # No assistant message found, nothing to clean\n return\n\n # Remove the last assistant message and all tool results after it\n removed_count = len(self.messages) - last_assistant_idx\n if removed_count > 0:\n self.messages = self.messages[:last_assistant_idx]\n print(f\"{Colors.DIM} Cleaned up {removed_count} incomplete message(s){Colors.RESET}\")\n\n def _estimate_tokens(self) -> int:\n \"\"\"Accurately calculate token count for message history using tiktoken\n\n Uses cl100k_base encoder (GPT-4/Claude/M2 compatible)\n \"\"\"\n try:\n # Use cl100k_base encoder (used by GPT-4 and most modern models)\n encoding = tiktoken.get_encoding(\"cl100k_base\")\n except Exception:\n # Fallback: if tiktoken initialization fails, use simple estimation\n return self._estimate_tokens_fallback()\n\n total_tokens = 0\n\n for msg in self.messages:\n # Count text content\n if isinstance(msg.content, str):\n total_tokens += len(encoding.encode(msg.content))\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n # Convert dict to string for calculation\n total_tokens += len(encoding.encode(str(block)))\n\n # Count thinking\n if msg.thinking:\n total_tokens += len(encoding.encode(msg.thinking))\n\n # Count tool_calls\n if msg.tool_calls:\n total_tokens += len(encoding.encode(str(msg.tool_calls)))\n\n # Metadata overhead per message (approximately 4 tokens)\n total_tokens += 4\n\n return total_tokens\n\n def _estimate_tokens_fallback(self) -> int:\n \"\"\"Fallback token estimation method (when tiktoken is unavailable)\"\"\"\n total_chars = 0\n for msg in self.messages:\n if isinstance(msg.content, str):\n total_chars += len(msg.content)\n elif isinstance(msg.content, list):\n for block in msg.content:\n if isinstance(block, dict):\n total_chars += len(str(block))\n\n if msg.thinking:\n total_chars += len(msg.thinking)\n\n if msg.tool_calls:\n total_chars += len(str(msg.tool_calls))\n\n # Rough estimation: average 2.5 characters = 1 token\n return int(total_chars / 2.5)\n\n async def _summarize_messages(self):\n \"\"\"Message history summarization: summarize conversations between user messages when tokens exceed limit\n\n Strategy (Agent mode):\n - Keep all user messages (these are user intents)\n - Summarize content between each user-user pair (agent execution process)\n - If last round is still executing (has agent/tool messages but no next user), also summarize\n - Structure: system -> user1 -> summary1 -> user2 -> summary2 -> user3 -> summary3 (if executing)\n\n Summary is triggered when EITHER:\n - Local token estimation exceeds limit\n - API reported total_tokens exceeds limit\n \"\"\"\n # Skip check if we just completed a summary (wait for next LLM call to update api_total_tokens)\n if self._skip_next_token_check:\n self._skip_next_token_check = False\n return\n\n estimated_tokens = self._estimate_tokens()\n\n # Check both local estimation and API reported tokens\n should_summarize = estimated_tokens > self.token_limit or self.api_total_tokens > self.token_limit\n\n # If neither exceeded, no summary needed\n if not should_summarize:\n return\n\n print(\n f\"\\n{Colors.BRIGHT_YELLOW}📊 Token usage - Local estimate: {estimated_tokens}, API reported: {self.api_total_tokens}, Limit: {self.token_limit}{Colors.RESET}\"\n )\n print(f\"{Colors.BRIGHT_YELLOW}🔄 Triggering message history summarization...{Colors.RESET}\")\n\n # Find all user message indices (skip system prompt)\n user_indices = [i for i, msg in enumerate(self.messages) if msg.role == \"user\" and i > 0]\n\n # Need at least 1 user message to perform summary\n if len(user_indices) < 1:\n print(f\"{Colors.BRIGHT_YELLOW}⚠️ Insufficient messages, cannot summarize{Colors.RESET}\")\n return\n\n # Build new message list\n new_messages = [self.messages[0]] # Keep system prompt\n summary_count = 0\n\n # Iterate through each user message and summarize the execution process after it\n for i, user_idx in enumerate(user_indices):\n # Add current user message\n new_messages.append(self.messages[user_idx])\n\n # Determine message range to summarize\n # If last user, go to end of message list; otherwise to before next user\n if i < len(user_indices) - 1:\n next_user_idx = user_indices[i + 1]\n else:\n next_user_idx = len(self.messages)\n\n # Extract execution messages for this round\n execution_messages = self.messages[user_idx + 1 : next_user_idx]\n\n # If there are execution messages in this round, summarize them\n if execution_messages:\n summary_text = await self._create_summary(execution_messages, i + 1)\n if summary_text:\n summary_message = Message(\n role=\"user\",\n content=f\"[Assistant Execution Summary]\\n\\n{summary_text}\",\n )\n new_messages.append(summary_message)\n summary_count += 1\n\n # Replace message list\n self.messages = new_messages\n\n # Skip next token check to avoid consecutive summary triggers\n # (api_total_tokens will be updated after next LLM call)\n self._skip_next_token_check = True\n\n new_tokens = self._estimate_tokens()\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary completed, local tokens: {estimated_tokens} → {new_tokens}{Colors.RESET}\")\n print(f\"{Colors.DIM} Structure: system + {len(user_indices)} user messages + {summary_count} summaries{Colors.RESET}\")\n print(f\"{Colors.DIM} Note: API token count will update on next LLM call{Colors.RESET}\")\n\n async def _create_summary(self, messages: list[Message], round_num: int) -> str:\n \"\"\"Create summary for one execution round\n\n Args:\n messages: List of messages to summarize\n round_num: Round number\n\n Returns:\n Summary text\n \"\"\"\n if not messages:\n return \"\"\n\n # Build summary content\n summary_content = f\"Round {round_num} execution process:\\n\\n\"\n for msg in messages:\n if msg.role == \"assistant\":\n content_text = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\"Assistant: {content_text}\\n\"\n if msg.tool_calls:\n tool_names = [tc.function.name for tc in msg.tool_calls]\n summary_content += f\" → Called tools: {', '.join(tool_names)}\\n\"\n elif msg.role == \"tool\":\n result_preview = msg.content if isinstance(msg.content, str) else str(msg.content)\n summary_content += f\" ← Tool returned: {result_preview}...\\n\"\n\n # Call LLM to generate concise summary\n try:\n summary_prompt = f\"\"\"Please provide a concise summary of the following Agent execution process:\n\n{summary_content}\n\nRequirements:\n1. Focus on what tasks were completed and which tools were called\n2. Keep key execution results and important findings\n3. Be concise and clear, within 1000 words\n4. Use English\n5. Do not include \"user\" related content, only summarize the Agent's execution process\"\"\"\n\n summary_msg = Message(role=\"user\", content=summary_prompt)\n response = await self.llm.generate(\n messages=[\n Message(\n role=\"system\",\n content=\"You are an assistant skilled at summarizing Agent execution processes.\",\n ),\n summary_msg,\n ]\n )\n\n summary_text = response.content\n print(f\"{Colors.BRIGHT_GREEN}✓ Summary for round {round_num} generated successfully{Colors.RESET}\")\n return summary_text\n\n except Exception as e:\n print(f\"{Colors.BRIGHT_RED}✗ Summary generation failed for round {round_num}: {e}{Colors.RESET}\")\n # Use simple text summary on failure\n return summary_content\n\n async def run(self, cancel_event: Optional[asyncio.Event] = None) -> str:\n \"\"\"Execute agent loop until task is complete or max steps reached.\n\n Args:\n cancel_event: Optional asyncio.Event that can be set to cancel execution.\n When set, the agent will stop at the next safe checkpoint\n (after completing the current step to keep messages consistent).\n\n Returns:\n The final response content, or error message (including cancellation message).\n \"\"\"\n # Set cancellation event (can also be set via self.cancel_event before calling run())\n if cancel_event is not None:\n self.cancel_event = cancel_event\n\n # Start new run, initialize log file\n self.logger.start_new_run()\n print(f\"{Colors.DIM}📝 Log file: {self.logger.get_log_file_path()}{Colors.RESET}\")\n\n step = 0\n run_start_time = perf_counter()\n\n while step < self.max_steps:\n # Check for cancellation at start of each step\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_start_time = perf_counter()\n # Check and summarize message history to prevent context overflow\n await self._summarize_messages()\n\n # Step header with proper width calculation\n BOX_WIDTH = 58\n step_text = f\"{Colors.BOLD}{Colors.BRIGHT_CYAN}💭 Step {step + 1}/{self.max_steps}{Colors.RESET}\"\n step_display_width = calculate_display_width(step_text)\n padding = max(0, BOX_WIDTH - 1 - step_display_width) # -1 for leading space\n\n print(f\"\\n{Colors.DIM}╭{'─' * BOX_WIDTH}╮{Colors.RESET}\")\n print(f\"{Colors.DIM}│{Colors.RESET} {step_text}{' ' * padding}{Colors.DIM}│{Colors.RESET}\")\n print(f\"{Colors.DIM}╰{'─' * BOX_WIDTH}╯{Colors.RESET}\")\n\n # Get tool list for LLM call\n tool_list = list(self.tools.values())\n\n # Log LLM request and call LLM with Tool objects directly\n self.logger.log_request(messages=self.messages, tools=tool_list)\n\n try:\n response = await self.llm.generate(messages=self.messages, tools=tool_list)\n except Exception as e:\n # Check if it's a retry exhausted error\n from .retry import RetryExhaustedError\n\n if isinstance(e, RetryExhaustedError):\n error_msg = f\"LLM call failed after {e.attempts} retries\\nLast error: {str(e.last_exception)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Retry failed:{Colors.RESET} {error_msg}\")\n else:\n error_msg = f\"LLM call failed: {str(e)}\"\n print(f\"\\n{Colors.BRIGHT_RED}❌ Error:{Colors.RESET} {error_msg}\")\n return error_msg\n\n # Accumulate API reported token usage\n if response.usage:\n self.api_total_tokens = response.usage.total_tokens\n\n # Log LLM response\n self.logger.log_response(\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n finish_reason=response.finish_reason,\n )\n\n # Add assistant message\n assistant_msg = Message(\n role=\"assistant\",\n content=response.content,\n thinking=response.thinking,\n tool_calls=response.tool_calls,\n )\n self.messages.append(assistant_msg)\n\n # Print thinking if present\n if response.thinking:\n print(f\"\\n{Colors.BOLD}{Colors.MAGENTA}🧠 Thinking:{Colors.RESET}\")\n print(f\"{Colors.DIM}{response.thinking}{Colors.RESET}\")\n\n # Print assistant response\n if response.content:\n print(f\"\\n{Colors.BOLD}{Colors.BRIGHT_BLUE}🤖 Assistant:{Colors.RESET}\")\n print(f\"{response.content}\")\n\n # Check if task is complete (no tool calls)\n if not response.tool_calls:\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n return response.content\n\n # Check for cancellation before executing tools\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n # Execute tool calls\n for tool_call in response.tool_calls:\n tool_call_id = tool_call.id\n function_name = tool_call.function.name\n arguments = tool_call.function.arguments\n\n # Tool call header\n print(f\"\\n{Colors.BRIGHT_YELLOW}🔧 Tool Call:{Colors.RESET} {Colors.BOLD}{Colors.CYAN}{function_name}{Colors.RESET}\")\n\n # Arguments (formatted display)\n print(f\"{Colors.DIM} Arguments:{Colors.RESET}\")\n # Truncate each argument value to avoid overly long output\n truncated_args = {}\n for key, value in arguments.items():\n value_str = str(value)\n if len(value_str) > 200:\n truncated_args[key] = value_str[:200] + \"...\"\n else:\n truncated_args[key] = value\n args_json = json.dumps(truncated_args, indent=2, ensure_ascii=False)\n for line in args_json.split(\"\\n\"):\n print(f\" {Colors.DIM}{line}{Colors.RESET}\")\n\n # Execute tool\n if function_name not in self.tools:\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Unknown tool: {function_name}\",\n )\n else:\n try:\n tool = self.tools[function_name]\n result = await tool.execute(**arguments)\n except Exception as e:\n # Catch all exceptions during tool execution, convert to failed ToolResult\n import traceback\n\n error_detail = f\"{type(e).__name__}: {str(e)}\"\n error_trace = traceback.format_exc()\n result = ToolResult(\n success=False,\n content=\"\",\n error=f\"Tool execution failed: {error_detail}\\n\\nTraceback:\\n{error_trace}\",\n )\n\n # Log tool execution result\n self.logger.log_tool_result(\n tool_name=function_name,\n arguments=arguments,\n result_success=result.success,\n result_content=result.content if result.success else None,\n result_error=result.error if not result.success else None,\n )\n\n # Print result\n if result.success:\n result_text = result.content\n if len(result_text) > 300:\n result_text = result_text[:300] + f\"{Colors.DIM}...{Colors.RESET}\"\n print(f\"{Colors.BRIGHT_GREEN}✓ Result:{Colors.RESET} {result_text}\")\n else:\n print(f\"{Colors.BRIGHT_RED}✗ Error:{Colors.RESET} {Colors.RED}{result.error}{Colors.RESET}\")\n\n # Add tool result message\n tool_msg = Message(\n role=\"tool\",\n content=result.content if result.success else f\"Error: {result.error}\",\n tool_call_id=tool_call_id,\n name=function_name,\n )\n self.messages.append(tool_msg)\n\n # Check for cancellation after each tool execution\n if self._check_cancelled():\n self._cleanup_incomplete_messages()\n cancel_msg = \"Task cancelled by user.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {cancel_msg}{Colors.RESET}\")\n return cancel_msg\n\n step_elapsed = perf_counter() - step_start_time\n total_elapsed = perf_counter() - run_start_time\n print(f\"\\n{Colors.DIM}⏱️ Step {step + 1} completed in {step_elapsed:.2f}s (total: {total_elapsed:.2f}s){Colors.RESET}\")\n\n step += 1\n\n # Max steps reached\n error_msg = f\"Task couldn't be completed after {self.max_steps} steps.\"\n print(f\"\\n{Colors.BRIGHT_YELLOW}⚠️ {error_msg}{Colors.RESET}\")\n return error_msg\n\n def get_history(self) -> list[Message]:\n \"\"\"Get message history.\"\"\"\n return self.messages.copy()\n\n\n# Source: mini_agent/schema/schema.py\nclass Message(BaseModel):\n \"\"\"Chat message.\"\"\"\n\n role: str # \"system\", \"user\", \"assistant\", \"tool\"\n content: str | list[dict[str, Any]] # Can be string or list of content blocks\n thinking: str | None = None # Extended thinking content for assistant messages\n tool_calls: list[ToolCall] | None = None\n tool_call_id: str | None = None\n name: str | None = None", "n_imports_parsed": 10, "n_files_resolved": 6, "n_chars_extracted": 21192}, "tests/test_skill_loader.py::111": {"resolved_imports": ["mini_agent/tools/skill_loader.py"], "used_names": ["Path", "SkillLoader", "tempfile"], "enclosing_function": "test_discover_skills", "extracted_code": "# Source: mini_agent/tools/skill_loader.py\nclass SkillLoader:\n \"\"\"Skill loader\"\"\"\n\n def __init__(self, skills_dir: str = \"./skills\"):\n \"\"\"\n Initialize Skill Loader\n\n Args:\n skills_dir: Skills directory path\n \"\"\"\n self.skills_dir = Path(skills_dir)\n self.loaded_skills: Dict[str, Skill] = {}\n\n def load_skill(self, skill_path: Path) -> Optional[Skill]:\n \"\"\"\n Load single skill from SKILL.md file\n\n Args:\n skill_path: SKILL.md file path\n\n Returns:\n Skill object, or None if loading fails\n \"\"\"\n try:\n content = skill_path.read_text(encoding=\"utf-8\")\n\n # Parse YAML frontmatter\n frontmatter_match = re.match(r\"^---\\n(.*?)\\n---\\n(.*)$\", content, re.DOTALL)\n\n if not frontmatter_match:\n print(f\"⚠️ {skill_path} missing YAML frontmatter\")\n return None\n\n frontmatter_text = frontmatter_match.group(1)\n skill_content = frontmatter_match.group(2).strip()\n\n # Parse YAML\n try:\n frontmatter = yaml.safe_load(frontmatter_text)\n except yaml.YAMLError as e:\n print(f\"❌ Failed to parse YAML frontmatter: {e}\")\n return None\n\n # Required fields\n if \"name\" not in frontmatter or \"description\" not in frontmatter:\n print(f\"⚠️ {skill_path} missing required fields (name or description)\")\n return None\n\n # Get skill directory (parent of SKILL.md)\n skill_dir = skill_path.parent\n\n # Replace relative paths in content with absolute paths\n # This ensures scripts and resources can be found from any working directory\n processed_content = self._process_skill_paths(skill_content, skill_dir)\n\n # Create Skill object\n skill = Skill(\n name=frontmatter[\"name\"],\n description=frontmatter[\"description\"],\n content=processed_content,\n license=frontmatter.get(\"license\"),\n allowed_tools=frontmatter.get(\"allowed-tools\"),\n metadata=frontmatter.get(\"metadata\"),\n skill_path=skill_path,\n )\n\n return skill\n\n except Exception as e:\n print(f\"❌ Failed to load skill ({skill_path}): {e}\")\n return None\n\n def _process_skill_paths(self, content: str, skill_dir: Path) -> str:\n \"\"\"\n Process skill content to replace relative paths with absolute paths.\n\n Supports Progressive Disclosure Level 3+: converts relative file references\n to absolute paths so Agent can easily read nested resources.\n\n Args:\n content: Original skill content\n skill_dir: Skill directory path\n\n Returns:\n Processed content with absolute paths\n \"\"\"\n import re\n\n # Pattern 1: Directory-based paths (scripts/, references/, assets/)\n # See https://agentskills.io/specification#optional-directories\n def replace_dir_path(match):\n prefix = match.group(1) # e.g., \"python \" or \"`\"\n rel_path = match.group(2) # e.g., \"scripts/with_server.py\"\n\n abs_path = skill_dir / rel_path\n if abs_path.exists():\n return f\"{prefix}{abs_path}\"\n return match.group(0)\n\n pattern_dirs = r\"(python\\s+|`)((?:scripts|references|assets)/[^\\s`\\)]+)\"\n content = re.sub(pattern_dirs, replace_dir_path, content)\n\n # Pattern 2: Direct markdown/document references (forms.md, reference.md, etc.)\n # Matches phrases like \"see reference.md\" or \"read forms.md\"\n def replace_doc_path(match):\n prefix = match.group(1) # e.g., \"see \", \"read \"\n filename = match.group(2) # e.g., \"reference.md\"\n suffix = match.group(3) # e.g., punctuation\n\n abs_path = skill_dir / filename\n if abs_path.exists():\n # Add helpful instruction for Agent\n return f\"{prefix}`{abs_path}` (use read_file to access){suffix}\"\n return match.group(0)\n\n # Match patterns like: \"see reference.md\" or \"read forms.md\"\n pattern_docs = r\"(see|read|refer to|check)\\s+([a-zA-Z0-9_-]+\\.(?:md|txt|json|yaml))([.,;\\s])\"\n content = re.sub(pattern_docs, replace_doc_path, content, flags=re.IGNORECASE)\n\n # Pattern 3: Markdown links - supports multiple formats:\n # - [`filename.md`](filename.md) - simple filename\n # - [text](./reference/file.md) - relative path with ./\n # - [text](scripts/file.js) - directory-based path\n # Matches patterns like: \"Read [`docx-js.md`](docx-js.md)\" or \"Load [Guide](./reference/guide.md)\"\n def replace_markdown_link(match):\n prefix = match.group(1) if match.group(1) else \"\" # e.g., \"Read \", \"Load \", or empty\n link_text = match.group(2) # e.g., \"`docx-js.md`\" or \"Guide\"\n filepath = match.group(3) # e.g., \"docx-js.md\", \"./reference/file.md\", \"scripts/file.js\"\n\n # Remove leading ./ if present\n clean_path = filepath[2:] if filepath.startswith(\"./\") else filepath\n\n abs_path = skill_dir / clean_path\n if abs_path.exists():\n # Preserve the link text style (with or without backticks)\n return f\"{prefix}[{link_text}](`{abs_path}`) (use read_file to access)\"\n return match.group(0)\n\n # Match markdown link patterns with optional prefix words\n # Captures: (optional prefix word) [link text] (complete file path including ./)\n pattern_markdown = (\n r\"(?:(Read|See|Check|Refer to|Load|View)\\s+)?\\[(`?[^`\\]]+`?)\\]\\(((?:\\./)?[^)]+\\.(?:md|txt|json|yaml|js|py|html))\\)\"\n )\n content = re.sub(pattern_markdown, replace_markdown_link, content, flags=re.IGNORECASE)\n\n return content\n\n def discover_skills(self) -> List[Skill]:\n \"\"\"\n Discover and load all skills in the skills directory\n\n Returns:\n List of Skills\n \"\"\"\n skills = []\n\n if not self.skills_dir.exists():\n print(f\"⚠️ Skills directory does not exist: {self.skills_dir}\")\n return skills\n\n # Recursively find all SKILL.md files\n for skill_file in self.skills_dir.rglob(\"SKILL.md\"):\n skill = self.load_skill(skill_file)\n if skill:\n skills.append(skill)\n self.loaded_skills[skill.name] = skill\n\n return skills\n\n def get_skill(self, name: str) -> Optional[Skill]:\n \"\"\"\n Get loaded skill\n\n Args:\n name: Skill name\n\n Returns:\n Skill object, or None if not found\n \"\"\"\n return self.loaded_skills.get(name)\n\n def list_skills(self) -> List[str]:\n \"\"\"\n List all loaded skill names\n\n Returns:\n List of skill names\n \"\"\"\n return list(self.loaded_skills.keys())\n\n def get_skills_metadata_prompt(self) -> str:\n \"\"\"\n Generate prompt containing ONLY metadata (name + description) for all skills.\n This implements Progressive Disclosure - Level 1.\n\n Returns:\n Metadata-only prompt string\n \"\"\"\n if not self.loaded_skills:\n return \"\"\n\n prompt_parts = [\"## Available Skills\\n\"]\n prompt_parts.append(\"You have access to specialized skills. Each skill provides expert guidance for specific tasks.\\n\")\n prompt_parts.append(\"Load a skill's full content using the appropriate skill tool when needed.\\n\")\n\n # List all skills with their descriptions\n for skill in self.loaded_skills.values():\n prompt_parts.append(f\"- `{skill.name}`: {skill.description}\")\n\n return \"\\n\".join(prompt_parts)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 7912}, "tests/test_skill_loader.py::42": {"resolved_imports": ["mini_agent/tools/skill_loader.py"], "used_names": ["Path", "SkillLoader", "tempfile"], "enclosing_function": "test_load_valid_skill", "extracted_code": "# Source: mini_agent/tools/skill_loader.py\nclass SkillLoader:\n \"\"\"Skill loader\"\"\"\n\n def __init__(self, skills_dir: str = \"./skills\"):\n \"\"\"\n Initialize Skill Loader\n\n Args:\n skills_dir: Skills directory path\n \"\"\"\n self.skills_dir = Path(skills_dir)\n self.loaded_skills: Dict[str, Skill] = {}\n\n def load_skill(self, skill_path: Path) -> Optional[Skill]:\n \"\"\"\n Load single skill from SKILL.md file\n\n Args:\n skill_path: SKILL.md file path\n\n Returns:\n Skill object, or None if loading fails\n \"\"\"\n try:\n content = skill_path.read_text(encoding=\"utf-8\")\n\n # Parse YAML frontmatter\n frontmatter_match = re.match(r\"^---\\n(.*?)\\n---\\n(.*)$\", content, re.DOTALL)\n\n if not frontmatter_match:\n print(f\"⚠️ {skill_path} missing YAML frontmatter\")\n return None\n\n frontmatter_text = frontmatter_match.group(1)\n skill_content = frontmatter_match.group(2).strip()\n\n # Parse YAML\n try:\n frontmatter = yaml.safe_load(frontmatter_text)\n except yaml.YAMLError as e:\n print(f\"❌ Failed to parse YAML frontmatter: {e}\")\n return None\n\n # Required fields\n if \"name\" not in frontmatter or \"description\" not in frontmatter:\n print(f\"⚠️ {skill_path} missing required fields (name or description)\")\n return None\n\n # Get skill directory (parent of SKILL.md)\n skill_dir = skill_path.parent\n\n # Replace relative paths in content with absolute paths\n # This ensures scripts and resources can be found from any working directory\n processed_content = self._process_skill_paths(skill_content, skill_dir)\n\n # Create Skill object\n skill = Skill(\n name=frontmatter[\"name\"],\n description=frontmatter[\"description\"],\n content=processed_content,\n license=frontmatter.get(\"license\"),\n allowed_tools=frontmatter.get(\"allowed-tools\"),\n metadata=frontmatter.get(\"metadata\"),\n skill_path=skill_path,\n )\n\n return skill\n\n except Exception as e:\n print(f\"❌ Failed to load skill ({skill_path}): {e}\")\n return None\n\n def _process_skill_paths(self, content: str, skill_dir: Path) -> str:\n \"\"\"\n Process skill content to replace relative paths with absolute paths.\n\n Supports Progressive Disclosure Level 3+: converts relative file references\n to absolute paths so Agent can easily read nested resources.\n\n Args:\n content: Original skill content\n skill_dir: Skill directory path\n\n Returns:\n Processed content with absolute paths\n \"\"\"\n import re\n\n # Pattern 1: Directory-based paths (scripts/, references/, assets/)\n # See https://agentskills.io/specification#optional-directories\n def replace_dir_path(match):\n prefix = match.group(1) # e.g., \"python \" or \"`\"\n rel_path = match.group(2) # e.g., \"scripts/with_server.py\"\n\n abs_path = skill_dir / rel_path\n if abs_path.exists():\n return f\"{prefix}{abs_path}\"\n return match.group(0)\n\n pattern_dirs = r\"(python\\s+|`)((?:scripts|references|assets)/[^\\s`\\)]+)\"\n content = re.sub(pattern_dirs, replace_dir_path, content)\n\n # Pattern 2: Direct markdown/document references (forms.md, reference.md, etc.)\n # Matches phrases like \"see reference.md\" or \"read forms.md\"\n def replace_doc_path(match):\n prefix = match.group(1) # e.g., \"see \", \"read \"\n filename = match.group(2) # e.g., \"reference.md\"\n suffix = match.group(3) # e.g., punctuation\n\n abs_path = skill_dir / filename\n if abs_path.exists():\n # Add helpful instruction for Agent\n return f\"{prefix}`{abs_path}` (use read_file to access){suffix}\"\n return match.group(0)\n\n # Match patterns like: \"see reference.md\" or \"read forms.md\"\n pattern_docs = r\"(see|read|refer to|check)\\s+([a-zA-Z0-9_-]+\\.(?:md|txt|json|yaml))([.,;\\s])\"\n content = re.sub(pattern_docs, replace_doc_path, content, flags=re.IGNORECASE)\n\n # Pattern 3: Markdown links - supports multiple formats:\n # - [`filename.md`](filename.md) - simple filename\n # - [text](./reference/file.md) - relative path with ./\n # - [text](scripts/file.js) - directory-based path\n # Matches patterns like: \"Read [`docx-js.md`](docx-js.md)\" or \"Load [Guide](./reference/guide.md)\"\n def replace_markdown_link(match):\n prefix = match.group(1) if match.group(1) else \"\" # e.g., \"Read \", \"Load \", or empty\n link_text = match.group(2) # e.g., \"`docx-js.md`\" or \"Guide\"\n filepath = match.group(3) # e.g., \"docx-js.md\", \"./reference/file.md\", \"scripts/file.js\"\n\n # Remove leading ./ if present\n clean_path = filepath[2:] if filepath.startswith(\"./\") else filepath\n\n abs_path = skill_dir / clean_path\n if abs_path.exists():\n # Preserve the link text style (with or without backticks)\n return f\"{prefix}[{link_text}](`{abs_path}`) (use read_file to access)\"\n return match.group(0)\n\n # Match markdown link patterns with optional prefix words\n # Captures: (optional prefix word) [link text] (complete file path including ./)\n pattern_markdown = (\n r\"(?:(Read|See|Check|Refer to|Load|View)\\s+)?\\[(`?[^`\\]]+`?)\\]\\(((?:\\./)?[^)]+\\.(?:md|txt|json|yaml|js|py|html))\\)\"\n )\n content = re.sub(pattern_markdown, replace_markdown_link, content, flags=re.IGNORECASE)\n\n return content\n\n def discover_skills(self) -> List[Skill]:\n \"\"\"\n Discover and load all skills in the skills directory\n\n Returns:\n List of Skills\n \"\"\"\n skills = []\n\n if not self.skills_dir.exists():\n print(f\"⚠️ Skills directory does not exist: {self.skills_dir}\")\n return skills\n\n # Recursively find all SKILL.md files\n for skill_file in self.skills_dir.rglob(\"SKILL.md\"):\n skill = self.load_skill(skill_file)\n if skill:\n skills.append(skill)\n self.loaded_skills[skill.name] = skill\n\n return skills\n\n def get_skill(self, name: str) -> Optional[Skill]:\n \"\"\"\n Get loaded skill\n\n Args:\n name: Skill name\n\n Returns:\n Skill object, or None if not found\n \"\"\"\n return self.loaded_skills.get(name)\n\n def list_skills(self) -> List[str]:\n \"\"\"\n List all loaded skill names\n\n Returns:\n List of skill names\n \"\"\"\n return list(self.loaded_skills.keys())\n\n def get_skills_metadata_prompt(self) -> str:\n \"\"\"\n Generate prompt containing ONLY metadata (name + description) for all skills.\n This implements Progressive Disclosure - Level 1.\n\n Returns:\n Metadata-only prompt string\n \"\"\"\n if not self.loaded_skills:\n return \"\"\n\n prompt_parts = [\"## Available Skills\\n\"]\n prompt_parts.append(\"You have access to specialized skills. Each skill provides expert guidance for specific tasks.\\n\")\n prompt_parts.append(\"Load a skill's full content using the appropriate skill tool when needed.\\n\")\n\n # List all skills with their descriptions\n for skill in self.loaded_skills.values():\n prompt_parts.append(f\"- `{skill.name}`: {skill.description}\")\n\n return \"\\n\".join(prompt_parts)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 7912}, "tests/test_skill_loader.py::76": {"resolved_imports": ["mini_agent/tools/skill_loader.py"], "used_names": ["Path", "SkillLoader", "tempfile"], "enclosing_function": "test_load_skill_with_metadata", "extracted_code": "# Source: mini_agent/tools/skill_loader.py\nclass SkillLoader:\n \"\"\"Skill loader\"\"\"\n\n def __init__(self, skills_dir: str = \"./skills\"):\n \"\"\"\n Initialize Skill Loader\n\n Args:\n skills_dir: Skills directory path\n \"\"\"\n self.skills_dir = Path(skills_dir)\n self.loaded_skills: Dict[str, Skill] = {}\n\n def load_skill(self, skill_path: Path) -> Optional[Skill]:\n \"\"\"\n Load single skill from SKILL.md file\n\n Args:\n skill_path: SKILL.md file path\n\n Returns:\n Skill object, or None if loading fails\n \"\"\"\n try:\n content = skill_path.read_text(encoding=\"utf-8\")\n\n # Parse YAML frontmatter\n frontmatter_match = re.match(r\"^---\\n(.*?)\\n---\\n(.*)$\", content, re.DOTALL)\n\n if not frontmatter_match:\n print(f\"⚠️ {skill_path} missing YAML frontmatter\")\n return None\n\n frontmatter_text = frontmatter_match.group(1)\n skill_content = frontmatter_match.group(2).strip()\n\n # Parse YAML\n try:\n frontmatter = yaml.safe_load(frontmatter_text)\n except yaml.YAMLError as e:\n print(f\"❌ Failed to parse YAML frontmatter: {e}\")\n return None\n\n # Required fields\n if \"name\" not in frontmatter or \"description\" not in frontmatter:\n print(f\"⚠️ {skill_path} missing required fields (name or description)\")\n return None\n\n # Get skill directory (parent of SKILL.md)\n skill_dir = skill_path.parent\n\n # Replace relative paths in content with absolute paths\n # This ensures scripts and resources can be found from any working directory\n processed_content = self._process_skill_paths(skill_content, skill_dir)\n\n # Create Skill object\n skill = Skill(\n name=frontmatter[\"name\"],\n description=frontmatter[\"description\"],\n content=processed_content,\n license=frontmatter.get(\"license\"),\n allowed_tools=frontmatter.get(\"allowed-tools\"),\n metadata=frontmatter.get(\"metadata\"),\n skill_path=skill_path,\n )\n\n return skill\n\n except Exception as e:\n print(f\"❌ Failed to load skill ({skill_path}): {e}\")\n return None\n\n def _process_skill_paths(self, content: str, skill_dir: Path) -> str:\n \"\"\"\n Process skill content to replace relative paths with absolute paths.\n\n Supports Progressive Disclosure Level 3+: converts relative file references\n to absolute paths so Agent can easily read nested resources.\n\n Args:\n content: Original skill content\n skill_dir: Skill directory path\n\n Returns:\n Processed content with absolute paths\n \"\"\"\n import re\n\n # Pattern 1: Directory-based paths (scripts/, references/, assets/)\n # See https://agentskills.io/specification#optional-directories\n def replace_dir_path(match):\n prefix = match.group(1) # e.g., \"python \" or \"`\"\n rel_path = match.group(2) # e.g., \"scripts/with_server.py\"\n\n abs_path = skill_dir / rel_path\n if abs_path.exists():\n return f\"{prefix}{abs_path}\"\n return match.group(0)\n\n pattern_dirs = r\"(python\\s+|`)((?:scripts|references|assets)/[^\\s`\\)]+)\"\n content = re.sub(pattern_dirs, replace_dir_path, content)\n\n # Pattern 2: Direct markdown/document references (forms.md, reference.md, etc.)\n # Matches phrases like \"see reference.md\" or \"read forms.md\"\n def replace_doc_path(match):\n prefix = match.group(1) # e.g., \"see \", \"read \"\n filename = match.group(2) # e.g., \"reference.md\"\n suffix = match.group(3) # e.g., punctuation\n\n abs_path = skill_dir / filename\n if abs_path.exists():\n # Add helpful instruction for Agent\n return f\"{prefix}`{abs_path}` (use read_file to access){suffix}\"\n return match.group(0)\n\n # Match patterns like: \"see reference.md\" or \"read forms.md\"\n pattern_docs = r\"(see|read|refer to|check)\\s+([a-zA-Z0-9_-]+\\.(?:md|txt|json|yaml))([.,;\\s])\"\n content = re.sub(pattern_docs, replace_doc_path, content, flags=re.IGNORECASE)\n\n # Pattern 3: Markdown links - supports multiple formats:\n # - [`filename.md`](filename.md) - simple filename\n # - [text](./reference/file.md) - relative path with ./\n # - [text](scripts/file.js) - directory-based path\n # Matches patterns like: \"Read [`docx-js.md`](docx-js.md)\" or \"Load [Guide](./reference/guide.md)\"\n def replace_markdown_link(match):\n prefix = match.group(1) if match.group(1) else \"\" # e.g., \"Read \", \"Load \", or empty\n link_text = match.group(2) # e.g., \"`docx-js.md`\" or \"Guide\"\n filepath = match.group(3) # e.g., \"docx-js.md\", \"./reference/file.md\", \"scripts/file.js\"\n\n # Remove leading ./ if present\n clean_path = filepath[2:] if filepath.startswith(\"./\") else filepath\n\n abs_path = skill_dir / clean_path\n if abs_path.exists():\n # Preserve the link text style (with or without backticks)\n return f\"{prefix}[{link_text}](`{abs_path}`) (use read_file to access)\"\n return match.group(0)\n\n # Match markdown link patterns with optional prefix words\n # Captures: (optional prefix word) [link text] (complete file path including ./)\n pattern_markdown = (\n r\"(?:(Read|See|Check|Refer to|Load|View)\\s+)?\\[(`?[^`\\]]+`?)\\]\\(((?:\\./)?[^)]+\\.(?:md|txt|json|yaml|js|py|html))\\)\"\n )\n content = re.sub(pattern_markdown, replace_markdown_link, content, flags=re.IGNORECASE)\n\n return content\n\n def discover_skills(self) -> List[Skill]:\n \"\"\"\n Discover and load all skills in the skills directory\n\n Returns:\n List of Skills\n \"\"\"\n skills = []\n\n if not self.skills_dir.exists():\n print(f\"⚠️ Skills directory does not exist: {self.skills_dir}\")\n return skills\n\n # Recursively find all SKILL.md files\n for skill_file in self.skills_dir.rglob(\"SKILL.md\"):\n skill = self.load_skill(skill_file)\n if skill:\n skills.append(skill)\n self.loaded_skills[skill.name] = skill\n\n return skills\n\n def get_skill(self, name: str) -> Optional[Skill]:\n \"\"\"\n Get loaded skill\n\n Args:\n name: Skill name\n\n Returns:\n Skill object, or None if not found\n \"\"\"\n return self.loaded_skills.get(name)\n\n def list_skills(self) -> List[str]:\n \"\"\"\n List all loaded skill names\n\n Returns:\n List of skill names\n \"\"\"\n return list(self.loaded_skills.keys())\n\n def get_skills_metadata_prompt(self) -> str:\n \"\"\"\n Generate prompt containing ONLY metadata (name + description) for all skills.\n This implements Progressive Disclosure - Level 1.\n\n Returns:\n Metadata-only prompt string\n \"\"\"\n if not self.loaded_skills:\n return \"\"\n\n prompt_parts = [\"## Available Skills\\n\"]\n prompt_parts.append(\"You have access to specialized skills. Each skill provides expert guidance for specific tasks.\\n\")\n prompt_parts.append(\"Load a skill's full content using the appropriate skill tool when needed.\\n\")\n\n # List all skills with their descriptions\n for skill in self.loaded_skills.values():\n prompt_parts.append(f\"- `{skill.name}`: {skill.description}\")\n\n return \"\\n\".join(prompt_parts)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 7912}, "tests/test_skill_loader.py::79": {"resolved_imports": ["mini_agent/tools/skill_loader.py"], "used_names": ["Path", "SkillLoader", "tempfile"], "enclosing_function": "test_load_skill_with_metadata", "extracted_code": "# Source: mini_agent/tools/skill_loader.py\nclass SkillLoader:\n \"\"\"Skill loader\"\"\"\n\n def __init__(self, skills_dir: str = \"./skills\"):\n \"\"\"\n Initialize Skill Loader\n\n Args:\n skills_dir: Skills directory path\n \"\"\"\n self.skills_dir = Path(skills_dir)\n self.loaded_skills: Dict[str, Skill] = {}\n\n def load_skill(self, skill_path: Path) -> Optional[Skill]:\n \"\"\"\n Load single skill from SKILL.md file\n\n Args:\n skill_path: SKILL.md file path\n\n Returns:\n Skill object, or None if loading fails\n \"\"\"\n try:\n content = skill_path.read_text(encoding=\"utf-8\")\n\n # Parse YAML frontmatter\n frontmatter_match = re.match(r\"^---\\n(.*?)\\n---\\n(.*)$\", content, re.DOTALL)\n\n if not frontmatter_match:\n print(f\"⚠️ {skill_path} missing YAML frontmatter\")\n return None\n\n frontmatter_text = frontmatter_match.group(1)\n skill_content = frontmatter_match.group(2).strip()\n\n # Parse YAML\n try:\n frontmatter = yaml.safe_load(frontmatter_text)\n except yaml.YAMLError as e:\n print(f\"❌ Failed to parse YAML frontmatter: {e}\")\n return None\n\n # Required fields\n if \"name\" not in frontmatter or \"description\" not in frontmatter:\n print(f\"⚠️ {skill_path} missing required fields (name or description)\")\n return None\n\n # Get skill directory (parent of SKILL.md)\n skill_dir = skill_path.parent\n\n # Replace relative paths in content with absolute paths\n # This ensures scripts and resources can be found from any working directory\n processed_content = self._process_skill_paths(skill_content, skill_dir)\n\n # Create Skill object\n skill = Skill(\n name=frontmatter[\"name\"],\n description=frontmatter[\"description\"],\n content=processed_content,\n license=frontmatter.get(\"license\"),\n allowed_tools=frontmatter.get(\"allowed-tools\"),\n metadata=frontmatter.get(\"metadata\"),\n skill_path=skill_path,\n )\n\n return skill\n\n except Exception as e:\n print(f\"❌ Failed to load skill ({skill_path}): {e}\")\n return None\n\n def _process_skill_paths(self, content: str, skill_dir: Path) -> str:\n \"\"\"\n Process skill content to replace relative paths with absolute paths.\n\n Supports Progressive Disclosure Level 3+: converts relative file references\n to absolute paths so Agent can easily read nested resources.\n\n Args:\n content: Original skill content\n skill_dir: Skill directory path\n\n Returns:\n Processed content with absolute paths\n \"\"\"\n import re\n\n # Pattern 1: Directory-based paths (scripts/, references/, assets/)\n # See https://agentskills.io/specification#optional-directories\n def replace_dir_path(match):\n prefix = match.group(1) # e.g., \"python \" or \"`\"\n rel_path = match.group(2) # e.g., \"scripts/with_server.py\"\n\n abs_path = skill_dir / rel_path\n if abs_path.exists():\n return f\"{prefix}{abs_path}\"\n return match.group(0)\n\n pattern_dirs = r\"(python\\s+|`)((?:scripts|references|assets)/[^\\s`\\)]+)\"\n content = re.sub(pattern_dirs, replace_dir_path, content)\n\n # Pattern 2: Direct markdown/document references (forms.md, reference.md, etc.)\n # Matches phrases like \"see reference.md\" or \"read forms.md\"\n def replace_doc_path(match):\n prefix = match.group(1) # e.g., \"see \", \"read \"\n filename = match.group(2) # e.g., \"reference.md\"\n suffix = match.group(3) # e.g., punctuation\n\n abs_path = skill_dir / filename\n if abs_path.exists():\n # Add helpful instruction for Agent\n return f\"{prefix}`{abs_path}` (use read_file to access){suffix}\"\n return match.group(0)\n\n # Match patterns like: \"see reference.md\" or \"read forms.md\"\n pattern_docs = r\"(see|read|refer to|check)\\s+([a-zA-Z0-9_-]+\\.(?:md|txt|json|yaml))([.,;\\s])\"\n content = re.sub(pattern_docs, replace_doc_path, content, flags=re.IGNORECASE)\n\n # Pattern 3: Markdown links - supports multiple formats:\n # - [`filename.md`](filename.md) - simple filename\n # - [text](./reference/file.md) - relative path with ./\n # - [text](scripts/file.js) - directory-based path\n # Matches patterns like: \"Read [`docx-js.md`](docx-js.md)\" or \"Load [Guide](./reference/guide.md)\"\n def replace_markdown_link(match):\n prefix = match.group(1) if match.group(1) else \"\" # e.g., \"Read \", \"Load \", or empty\n link_text = match.group(2) # e.g., \"`docx-js.md`\" or \"Guide\"\n filepath = match.group(3) # e.g., \"docx-js.md\", \"./reference/file.md\", \"scripts/file.js\"\n\n # Remove leading ./ if present\n clean_path = filepath[2:] if filepath.startswith(\"./\") else filepath\n\n abs_path = skill_dir / clean_path\n if abs_path.exists():\n # Preserve the link text style (with or without backticks)\n return f\"{prefix}[{link_text}](`{abs_path}`) (use read_file to access)\"\n return match.group(0)\n\n # Match markdown link patterns with optional prefix words\n # Captures: (optional prefix word) [link text] (complete file path including ./)\n pattern_markdown = (\n r\"(?:(Read|See|Check|Refer to|Load|View)\\s+)?\\[(`?[^`\\]]+`?)\\]\\(((?:\\./)?[^)]+\\.(?:md|txt|json|yaml|js|py|html))\\)\"\n )\n content = re.sub(pattern_markdown, replace_markdown_link, content, flags=re.IGNORECASE)\n\n return content\n\n def discover_skills(self) -> List[Skill]:\n \"\"\"\n Discover and load all skills in the skills directory\n\n Returns:\n List of Skills\n \"\"\"\n skills = []\n\n if not self.skills_dir.exists():\n print(f\"⚠️ Skills directory does not exist: {self.skills_dir}\")\n return skills\n\n # Recursively find all SKILL.md files\n for skill_file in self.skills_dir.rglob(\"SKILL.md\"):\n skill = self.load_skill(skill_file)\n if skill:\n skills.append(skill)\n self.loaded_skills[skill.name] = skill\n\n return skills\n\n def get_skill(self, name: str) -> Optional[Skill]:\n \"\"\"\n Get loaded skill\n\n Args:\n name: Skill name\n\n Returns:\n Skill object, or None if not found\n \"\"\"\n return self.loaded_skills.get(name)\n\n def list_skills(self) -> List[str]:\n \"\"\"\n List all loaded skill names\n\n Returns:\n List of skill names\n \"\"\"\n return list(self.loaded_skills.keys())\n\n def get_skills_metadata_prompt(self) -> str:\n \"\"\"\n Generate prompt containing ONLY metadata (name + description) for all skills.\n This implements Progressive Disclosure - Level 1.\n\n Returns:\n Metadata-only prompt string\n \"\"\"\n if not self.loaded_skills:\n return \"\"\n\n prompt_parts = [\"## Available Skills\\n\"]\n prompt_parts.append(\"You have access to specialized skills. Each skill provides expert guidance for specific tasks.\\n\")\n prompt_parts.append(\"Load a skill's full content using the appropriate skill tool when needed.\\n\")\n\n # List all skills with their descriptions\n for skill in self.loaded_skills.values():\n prompt_parts.append(f\"- `{skill.name}`: {skill.description}\")\n\n return \"\\n\".join(prompt_parts)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 7912}, "tests/test_skill_loader.py::272": {"resolved_imports": ["mini_agent/tools/skill_loader.py"], "used_names": ["Path", "SkillLoader", "tempfile"], "enclosing_function": "test_skill_to_prompt_includes_root_directory", "extracted_code": "# Source: mini_agent/tools/skill_loader.py\nclass SkillLoader:\n \"\"\"Skill loader\"\"\"\n\n def __init__(self, skills_dir: str = \"./skills\"):\n \"\"\"\n Initialize Skill Loader\n\n Args:\n skills_dir: Skills directory path\n \"\"\"\n self.skills_dir = Path(skills_dir)\n self.loaded_skills: Dict[str, Skill] = {}\n\n def load_skill(self, skill_path: Path) -> Optional[Skill]:\n \"\"\"\n Load single skill from SKILL.md file\n\n Args:\n skill_path: SKILL.md file path\n\n Returns:\n Skill object, or None if loading fails\n \"\"\"\n try:\n content = skill_path.read_text(encoding=\"utf-8\")\n\n # Parse YAML frontmatter\n frontmatter_match = re.match(r\"^---\\n(.*?)\\n---\\n(.*)$\", content, re.DOTALL)\n\n if not frontmatter_match:\n print(f\"⚠️ {skill_path} missing YAML frontmatter\")\n return None\n\n frontmatter_text = frontmatter_match.group(1)\n skill_content = frontmatter_match.group(2).strip()\n\n # Parse YAML\n try:\n frontmatter = yaml.safe_load(frontmatter_text)\n except yaml.YAMLError as e:\n print(f\"❌ Failed to parse YAML frontmatter: {e}\")\n return None\n\n # Required fields\n if \"name\" not in frontmatter or \"description\" not in frontmatter:\n print(f\"⚠️ {skill_path} missing required fields (name or description)\")\n return None\n\n # Get skill directory (parent of SKILL.md)\n skill_dir = skill_path.parent\n\n # Replace relative paths in content with absolute paths\n # This ensures scripts and resources can be found from any working directory\n processed_content = self._process_skill_paths(skill_content, skill_dir)\n\n # Create Skill object\n skill = Skill(\n name=frontmatter[\"name\"],\n description=frontmatter[\"description\"],\n content=processed_content,\n license=frontmatter.get(\"license\"),\n allowed_tools=frontmatter.get(\"allowed-tools\"),\n metadata=frontmatter.get(\"metadata\"),\n skill_path=skill_path,\n )\n\n return skill\n\n except Exception as e:\n print(f\"❌ Failed to load skill ({skill_path}): {e}\")\n return None\n\n def _process_skill_paths(self, content: str, skill_dir: Path) -> str:\n \"\"\"\n Process skill content to replace relative paths with absolute paths.\n\n Supports Progressive Disclosure Level 3+: converts relative file references\n to absolute paths so Agent can easily read nested resources.\n\n Args:\n content: Original skill content\n skill_dir: Skill directory path\n\n Returns:\n Processed content with absolute paths\n \"\"\"\n import re\n\n # Pattern 1: Directory-based paths (scripts/, references/, assets/)\n # See https://agentskills.io/specification#optional-directories\n def replace_dir_path(match):\n prefix = match.group(1) # e.g., \"python \" or \"`\"\n rel_path = match.group(2) # e.g., \"scripts/with_server.py\"\n\n abs_path = skill_dir / rel_path\n if abs_path.exists():\n return f\"{prefix}{abs_path}\"\n return match.group(0)\n\n pattern_dirs = r\"(python\\s+|`)((?:scripts|references|assets)/[^\\s`\\)]+)\"\n content = re.sub(pattern_dirs, replace_dir_path, content)\n\n # Pattern 2: Direct markdown/document references (forms.md, reference.md, etc.)\n # Matches phrases like \"see reference.md\" or \"read forms.md\"\n def replace_doc_path(match):\n prefix = match.group(1) # e.g., \"see \", \"read \"\n filename = match.group(2) # e.g., \"reference.md\"\n suffix = match.group(3) # e.g., punctuation\n\n abs_path = skill_dir / filename\n if abs_path.exists():\n # Add helpful instruction for Agent\n return f\"{prefix}`{abs_path}` (use read_file to access){suffix}\"\n return match.group(0)\n\n # Match patterns like: \"see reference.md\" or \"read forms.md\"\n pattern_docs = r\"(see|read|refer to|check)\\s+([a-zA-Z0-9_-]+\\.(?:md|txt|json|yaml))([.,;\\s])\"\n content = re.sub(pattern_docs, replace_doc_path, content, flags=re.IGNORECASE)\n\n # Pattern 3: Markdown links - supports multiple formats:\n # - [`filename.md`](filename.md) - simple filename\n # - [text](./reference/file.md) - relative path with ./\n # - [text](scripts/file.js) - directory-based path\n # Matches patterns like: \"Read [`docx-js.md`](docx-js.md)\" or \"Load [Guide](./reference/guide.md)\"\n def replace_markdown_link(match):\n prefix = match.group(1) if match.group(1) else \"\" # e.g., \"Read \", \"Load \", or empty\n link_text = match.group(2) # e.g., \"`docx-js.md`\" or \"Guide\"\n filepath = match.group(3) # e.g., \"docx-js.md\", \"./reference/file.md\", \"scripts/file.js\"\n\n # Remove leading ./ if present\n clean_path = filepath[2:] if filepath.startswith(\"./\") else filepath\n\n abs_path = skill_dir / clean_path\n if abs_path.exists():\n # Preserve the link text style (with or without backticks)\n return f\"{prefix}[{link_text}](`{abs_path}`) (use read_file to access)\"\n return match.group(0)\n\n # Match markdown link patterns with optional prefix words\n # Captures: (optional prefix word) [link text] (complete file path including ./)\n pattern_markdown = (\n r\"(?:(Read|See|Check|Refer to|Load|View)\\s+)?\\[(`?[^`\\]]+`?)\\]\\(((?:\\./)?[^)]+\\.(?:md|txt|json|yaml|js|py|html))\\)\"\n )\n content = re.sub(pattern_markdown, replace_markdown_link, content, flags=re.IGNORECASE)\n\n return content\n\n def discover_skills(self) -> List[Skill]:\n \"\"\"\n Discover and load all skills in the skills directory\n\n Returns:\n List of Skills\n \"\"\"\n skills = []\n\n if not self.skills_dir.exists():\n print(f\"⚠️ Skills directory does not exist: {self.skills_dir}\")\n return skills\n\n # Recursively find all SKILL.md files\n for skill_file in self.skills_dir.rglob(\"SKILL.md\"):\n skill = self.load_skill(skill_file)\n if skill:\n skills.append(skill)\n self.loaded_skills[skill.name] = skill\n\n return skills\n\n def get_skill(self, name: str) -> Optional[Skill]:\n \"\"\"\n Get loaded skill\n\n Args:\n name: Skill name\n\n Returns:\n Skill object, or None if not found\n \"\"\"\n return self.loaded_skills.get(name)\n\n def list_skills(self) -> List[str]:\n \"\"\"\n List all loaded skill names\n\n Returns:\n List of skill names\n \"\"\"\n return list(self.loaded_skills.keys())\n\n def get_skills_metadata_prompt(self) -> str:\n \"\"\"\n Generate prompt containing ONLY metadata (name + description) for all skills.\n This implements Progressive Disclosure - Level 1.\n\n Returns:\n Metadata-only prompt string\n \"\"\"\n if not self.loaded_skills:\n return \"\"\n\n prompt_parts = [\"## Available Skills\\n\"]\n prompt_parts.append(\"You have access to specialized skills. Each skill provides expert guidance for specific tasks.\\n\")\n prompt_parts.append(\"Load a skill's full content using the appropriate skill tool when needed.\\n\")\n\n # List all skills with their descriptions\n for skill in self.loaded_skills.values():\n prompt_parts.append(f\"- `{skill.name}`: {skill.description}\")\n\n return \"\\n\".join(prompt_parts)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 7912}, "tests/test_skill_loader.py::43": {"resolved_imports": ["mini_agent/tools/skill_loader.py"], "used_names": ["Path", "SkillLoader", "tempfile"], "enclosing_function": "test_load_valid_skill", "extracted_code": "# Source: mini_agent/tools/skill_loader.py\nclass SkillLoader:\n \"\"\"Skill loader\"\"\"\n\n def __init__(self, skills_dir: str = \"./skills\"):\n \"\"\"\n Initialize Skill Loader\n\n Args:\n skills_dir: Skills directory path\n \"\"\"\n self.skills_dir = Path(skills_dir)\n self.loaded_skills: Dict[str, Skill] = {}\n\n def load_skill(self, skill_path: Path) -> Optional[Skill]:\n \"\"\"\n Load single skill from SKILL.md file\n\n Args:\n skill_path: SKILL.md file path\n\n Returns:\n Skill object, or None if loading fails\n \"\"\"\n try:\n content = skill_path.read_text(encoding=\"utf-8\")\n\n # Parse YAML frontmatter\n frontmatter_match = re.match(r\"^---\\n(.*?)\\n---\\n(.*)$\", content, re.DOTALL)\n\n if not frontmatter_match:\n print(f\"⚠️ {skill_path} missing YAML frontmatter\")\n return None\n\n frontmatter_text = frontmatter_match.group(1)\n skill_content = frontmatter_match.group(2).strip()\n\n # Parse YAML\n try:\n frontmatter = yaml.safe_load(frontmatter_text)\n except yaml.YAMLError as e:\n print(f\"❌ Failed to parse YAML frontmatter: {e}\")\n return None\n\n # Required fields\n if \"name\" not in frontmatter or \"description\" not in frontmatter:\n print(f\"⚠️ {skill_path} missing required fields (name or description)\")\n return None\n\n # Get skill directory (parent of SKILL.md)\n skill_dir = skill_path.parent\n\n # Replace relative paths in content with absolute paths\n # This ensures scripts and resources can be found from any working directory\n processed_content = self._process_skill_paths(skill_content, skill_dir)\n\n # Create Skill object\n skill = Skill(\n name=frontmatter[\"name\"],\n description=frontmatter[\"description\"],\n content=processed_content,\n license=frontmatter.get(\"license\"),\n allowed_tools=frontmatter.get(\"allowed-tools\"),\n metadata=frontmatter.get(\"metadata\"),\n skill_path=skill_path,\n )\n\n return skill\n\n except Exception as e:\n print(f\"❌ Failed to load skill ({skill_path}): {e}\")\n return None\n\n def _process_skill_paths(self, content: str, skill_dir: Path) -> str:\n \"\"\"\n Process skill content to replace relative paths with absolute paths.\n\n Supports Progressive Disclosure Level 3+: converts relative file references\n to absolute paths so Agent can easily read nested resources.\n\n Args:\n content: Original skill content\n skill_dir: Skill directory path\n\n Returns:\n Processed content with absolute paths\n \"\"\"\n import re\n\n # Pattern 1: Directory-based paths (scripts/, references/, assets/)\n # See https://agentskills.io/specification#optional-directories\n def replace_dir_path(match):\n prefix = match.group(1) # e.g., \"python \" or \"`\"\n rel_path = match.group(2) # e.g., \"scripts/with_server.py\"\n\n abs_path = skill_dir / rel_path\n if abs_path.exists():\n return f\"{prefix}{abs_path}\"\n return match.group(0)\n\n pattern_dirs = r\"(python\\s+|`)((?:scripts|references|assets)/[^\\s`\\)]+)\"\n content = re.sub(pattern_dirs, replace_dir_path, content)\n\n # Pattern 2: Direct markdown/document references (forms.md, reference.md, etc.)\n # Matches phrases like \"see reference.md\" or \"read forms.md\"\n def replace_doc_path(match):\n prefix = match.group(1) # e.g., \"see \", \"read \"\n filename = match.group(2) # e.g., \"reference.md\"\n suffix = match.group(3) # e.g., punctuation\n\n abs_path = skill_dir / filename\n if abs_path.exists():\n # Add helpful instruction for Agent\n return f\"{prefix}`{abs_path}` (use read_file to access){suffix}\"\n return match.group(0)\n\n # Match patterns like: \"see reference.md\" or \"read forms.md\"\n pattern_docs = r\"(see|read|refer to|check)\\s+([a-zA-Z0-9_-]+\\.(?:md|txt|json|yaml))([.,;\\s])\"\n content = re.sub(pattern_docs, replace_doc_path, content, flags=re.IGNORECASE)\n\n # Pattern 3: Markdown links - supports multiple formats:\n # - [`filename.md`](filename.md) - simple filename\n # - [text](./reference/file.md) - relative path with ./\n # - [text](scripts/file.js) - directory-based path\n # Matches patterns like: \"Read [`docx-js.md`](docx-js.md)\" or \"Load [Guide](./reference/guide.md)\"\n def replace_markdown_link(match):\n prefix = match.group(1) if match.group(1) else \"\" # e.g., \"Read \", \"Load \", or empty\n link_text = match.group(2) # e.g., \"`docx-js.md`\" or \"Guide\"\n filepath = match.group(3) # e.g., \"docx-js.md\", \"./reference/file.md\", \"scripts/file.js\"\n\n # Remove leading ./ if present\n clean_path = filepath[2:] if filepath.startswith(\"./\") else filepath\n\n abs_path = skill_dir / clean_path\n if abs_path.exists():\n # Preserve the link text style (with or without backticks)\n return f\"{prefix}[{link_text}](`{abs_path}`) (use read_file to access)\"\n return match.group(0)\n\n # Match markdown link patterns with optional prefix words\n # Captures: (optional prefix word) [link text] (complete file path including ./)\n pattern_markdown = (\n r\"(?:(Read|See|Check|Refer to|Load|View)\\s+)?\\[(`?[^`\\]]+`?)\\]\\(((?:\\./)?[^)]+\\.(?:md|txt|json|yaml|js|py|html))\\)\"\n )\n content = re.sub(pattern_markdown, replace_markdown_link, content, flags=re.IGNORECASE)\n\n return content\n\n def discover_skills(self) -> List[Skill]:\n \"\"\"\n Discover and load all skills in the skills directory\n\n Returns:\n List of Skills\n \"\"\"\n skills = []\n\n if not self.skills_dir.exists():\n print(f\"⚠️ Skills directory does not exist: {self.skills_dir}\")\n return skills\n\n # Recursively find all SKILL.md files\n for skill_file in self.skills_dir.rglob(\"SKILL.md\"):\n skill = self.load_skill(skill_file)\n if skill:\n skills.append(skill)\n self.loaded_skills[skill.name] = skill\n\n return skills\n\n def get_skill(self, name: str) -> Optional[Skill]:\n \"\"\"\n Get loaded skill\n\n Args:\n name: Skill name\n\n Returns:\n Skill object, or None if not found\n \"\"\"\n return self.loaded_skills.get(name)\n\n def list_skills(self) -> List[str]:\n \"\"\"\n List all loaded skill names\n\n Returns:\n List of skill names\n \"\"\"\n return list(self.loaded_skills.keys())\n\n def get_skills_metadata_prompt(self) -> str:\n \"\"\"\n Generate prompt containing ONLY metadata (name + description) for all skills.\n This implements Progressive Disclosure - Level 1.\n\n Returns:\n Metadata-only prompt string\n \"\"\"\n if not self.loaded_skills:\n return \"\"\n\n prompt_parts = [\"## Available Skills\\n\"]\n prompt_parts.append(\"You have access to specialized skills. Each skill provides expert guidance for specific tasks.\\n\")\n prompt_parts.append(\"Load a skill's full content using the appropriate skill tool when needed.\\n\")\n\n # List all skills with their descriptions\n for skill in self.loaded_skills.values():\n prompt_parts.append(f\"- `{skill.name}`: {skill.description}\")\n\n return \"\\n\".join(prompt_parts)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 7912}, "tests/test_skill_loader.py::45": {"resolved_imports": ["mini_agent/tools/skill_loader.py"], "used_names": ["Path", "SkillLoader", "tempfile"], "enclosing_function": "test_load_valid_skill", "extracted_code": "# Source: mini_agent/tools/skill_loader.py\nclass SkillLoader:\n \"\"\"Skill loader\"\"\"\n\n def __init__(self, skills_dir: str = \"./skills\"):\n \"\"\"\n Initialize Skill Loader\n\n Args:\n skills_dir: Skills directory path\n \"\"\"\n self.skills_dir = Path(skills_dir)\n self.loaded_skills: Dict[str, Skill] = {}\n\n def load_skill(self, skill_path: Path) -> Optional[Skill]:\n \"\"\"\n Load single skill from SKILL.md file\n\n Args:\n skill_path: SKILL.md file path\n\n Returns:\n Skill object, or None if loading fails\n \"\"\"\n try:\n content = skill_path.read_text(encoding=\"utf-8\")\n\n # Parse YAML frontmatter\n frontmatter_match = re.match(r\"^---\\n(.*?)\\n---\\n(.*)$\", content, re.DOTALL)\n\n if not frontmatter_match:\n print(f\"⚠️ {skill_path} missing YAML frontmatter\")\n return None\n\n frontmatter_text = frontmatter_match.group(1)\n skill_content = frontmatter_match.group(2).strip()\n\n # Parse YAML\n try:\n frontmatter = yaml.safe_load(frontmatter_text)\n except yaml.YAMLError as e:\n print(f\"❌ Failed to parse YAML frontmatter: {e}\")\n return None\n\n # Required fields\n if \"name\" not in frontmatter or \"description\" not in frontmatter:\n print(f\"⚠️ {skill_path} missing required fields (name or description)\")\n return None\n\n # Get skill directory (parent of SKILL.md)\n skill_dir = skill_path.parent\n\n # Replace relative paths in content with absolute paths\n # This ensures scripts and resources can be found from any working directory\n processed_content = self._process_skill_paths(skill_content, skill_dir)\n\n # Create Skill object\n skill = Skill(\n name=frontmatter[\"name\"],\n description=frontmatter[\"description\"],\n content=processed_content,\n license=frontmatter.get(\"license\"),\n allowed_tools=frontmatter.get(\"allowed-tools\"),\n metadata=frontmatter.get(\"metadata\"),\n skill_path=skill_path,\n )\n\n return skill\n\n except Exception as e:\n print(f\"❌ Failed to load skill ({skill_path}): {e}\")\n return None\n\n def _process_skill_paths(self, content: str, skill_dir: Path) -> str:\n \"\"\"\n Process skill content to replace relative paths with absolute paths.\n\n Supports Progressive Disclosure Level 3+: converts relative file references\n to absolute paths so Agent can easily read nested resources.\n\n Args:\n content: Original skill content\n skill_dir: Skill directory path\n\n Returns:\n Processed content with absolute paths\n \"\"\"\n import re\n\n # Pattern 1: Directory-based paths (scripts/, references/, assets/)\n # See https://agentskills.io/specification#optional-directories\n def replace_dir_path(match):\n prefix = match.group(1) # e.g., \"python \" or \"`\"\n rel_path = match.group(2) # e.g., \"scripts/with_server.py\"\n\n abs_path = skill_dir / rel_path\n if abs_path.exists():\n return f\"{prefix}{abs_path}\"\n return match.group(0)\n\n pattern_dirs = r\"(python\\s+|`)((?:scripts|references|assets)/[^\\s`\\)]+)\"\n content = re.sub(pattern_dirs, replace_dir_path, content)\n\n # Pattern 2: Direct markdown/document references (forms.md, reference.md, etc.)\n # Matches phrases like \"see reference.md\" or \"read forms.md\"\n def replace_doc_path(match):\n prefix = match.group(1) # e.g., \"see \", \"read \"\n filename = match.group(2) # e.g., \"reference.md\"\n suffix = match.group(3) # e.g., punctuation\n\n abs_path = skill_dir / filename\n if abs_path.exists():\n # Add helpful instruction for Agent\n return f\"{prefix}`{abs_path}` (use read_file to access){suffix}\"\n return match.group(0)\n\n # Match patterns like: \"see reference.md\" or \"read forms.md\"\n pattern_docs = r\"(see|read|refer to|check)\\s+([a-zA-Z0-9_-]+\\.(?:md|txt|json|yaml))([.,;\\s])\"\n content = re.sub(pattern_docs, replace_doc_path, content, flags=re.IGNORECASE)\n\n # Pattern 3: Markdown links - supports multiple formats:\n # - [`filename.md`](filename.md) - simple filename\n # - [text](./reference/file.md) - relative path with ./\n # - [text](scripts/file.js) - directory-based path\n # Matches patterns like: \"Read [`docx-js.md`](docx-js.md)\" or \"Load [Guide](./reference/guide.md)\"\n def replace_markdown_link(match):\n prefix = match.group(1) if match.group(1) else \"\" # e.g., \"Read \", \"Load \", or empty\n link_text = match.group(2) # e.g., \"`docx-js.md`\" or \"Guide\"\n filepath = match.group(3) # e.g., \"docx-js.md\", \"./reference/file.md\", \"scripts/file.js\"\n\n # Remove leading ./ if present\n clean_path = filepath[2:] if filepath.startswith(\"./\") else filepath\n\n abs_path = skill_dir / clean_path\n if abs_path.exists():\n # Preserve the link text style (with or without backticks)\n return f\"{prefix}[{link_text}](`{abs_path}`) (use read_file to access)\"\n return match.group(0)\n\n # Match markdown link patterns with optional prefix words\n # Captures: (optional prefix word) [link text] (complete file path including ./)\n pattern_markdown = (\n r\"(?:(Read|See|Check|Refer to|Load|View)\\s+)?\\[(`?[^`\\]]+`?)\\]\\(((?:\\./)?[^)]+\\.(?:md|txt|json|yaml|js|py|html))\\)\"\n )\n content = re.sub(pattern_markdown, replace_markdown_link, content, flags=re.IGNORECASE)\n\n return content\n\n def discover_skills(self) -> List[Skill]:\n \"\"\"\n Discover and load all skills in the skills directory\n\n Returns:\n List of Skills\n \"\"\"\n skills = []\n\n if not self.skills_dir.exists():\n print(f\"⚠️ Skills directory does not exist: {self.skills_dir}\")\n return skills\n\n # Recursively find all SKILL.md files\n for skill_file in self.skills_dir.rglob(\"SKILL.md\"):\n skill = self.load_skill(skill_file)\n if skill:\n skills.append(skill)\n self.loaded_skills[skill.name] = skill\n\n return skills\n\n def get_skill(self, name: str) -> Optional[Skill]:\n \"\"\"\n Get loaded skill\n\n Args:\n name: Skill name\n\n Returns:\n Skill object, or None if not found\n \"\"\"\n return self.loaded_skills.get(name)\n\n def list_skills(self) -> List[str]:\n \"\"\"\n List all loaded skill names\n\n Returns:\n List of skill names\n \"\"\"\n return list(self.loaded_skills.keys())\n\n def get_skills_metadata_prompt(self) -> str:\n \"\"\"\n Generate prompt containing ONLY metadata (name + description) for all skills.\n This implements Progressive Disclosure - Level 1.\n\n Returns:\n Metadata-only prompt string\n \"\"\"\n if not self.loaded_skills:\n return \"\"\n\n prompt_parts = [\"## Available Skills\\n\"]\n prompt_parts.append(\"You have access to specialized skills. Each skill provides expert guidance for specific tasks.\\n\")\n prompt_parts.append(\"Load a skill's full content using the appropriate skill tool when needed.\\n\")\n\n # List all skills with their descriptions\n for skill in self.loaded_skills.values():\n prompt_parts.append(f\"- `{skill.name}`: {skill.description}\")\n\n return \"\\n\".join(prompt_parts)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 7912}, "tests/test_skill_loader.py::78": {"resolved_imports": ["mini_agent/tools/skill_loader.py"], "used_names": ["Path", "SkillLoader", "tempfile"], "enclosing_function": "test_load_skill_with_metadata", "extracted_code": "# Source: mini_agent/tools/skill_loader.py\nclass SkillLoader:\n \"\"\"Skill loader\"\"\"\n\n def __init__(self, skills_dir: str = \"./skills\"):\n \"\"\"\n Initialize Skill Loader\n\n Args:\n skills_dir: Skills directory path\n \"\"\"\n self.skills_dir = Path(skills_dir)\n self.loaded_skills: Dict[str, Skill] = {}\n\n def load_skill(self, skill_path: Path) -> Optional[Skill]:\n \"\"\"\n Load single skill from SKILL.md file\n\n Args:\n skill_path: SKILL.md file path\n\n Returns:\n Skill object, or None if loading fails\n \"\"\"\n try:\n content = skill_path.read_text(encoding=\"utf-8\")\n\n # Parse YAML frontmatter\n frontmatter_match = re.match(r\"^---\\n(.*?)\\n---\\n(.*)$\", content, re.DOTALL)\n\n if not frontmatter_match:\n print(f\"⚠️ {skill_path} missing YAML frontmatter\")\n return None\n\n frontmatter_text = frontmatter_match.group(1)\n skill_content = frontmatter_match.group(2).strip()\n\n # Parse YAML\n try:\n frontmatter = yaml.safe_load(frontmatter_text)\n except yaml.YAMLError as e:\n print(f\"❌ Failed to parse YAML frontmatter: {e}\")\n return None\n\n # Required fields\n if \"name\" not in frontmatter or \"description\" not in frontmatter:\n print(f\"⚠️ {skill_path} missing required fields (name or description)\")\n return None\n\n # Get skill directory (parent of SKILL.md)\n skill_dir = skill_path.parent\n\n # Replace relative paths in content with absolute paths\n # This ensures scripts and resources can be found from any working directory\n processed_content = self._process_skill_paths(skill_content, skill_dir)\n\n # Create Skill object\n skill = Skill(\n name=frontmatter[\"name\"],\n description=frontmatter[\"description\"],\n content=processed_content,\n license=frontmatter.get(\"license\"),\n allowed_tools=frontmatter.get(\"allowed-tools\"),\n metadata=frontmatter.get(\"metadata\"),\n skill_path=skill_path,\n )\n\n return skill\n\n except Exception as e:\n print(f\"❌ Failed to load skill ({skill_path}): {e}\")\n return None\n\n def _process_skill_paths(self, content: str, skill_dir: Path) -> str:\n \"\"\"\n Process skill content to replace relative paths with absolute paths.\n\n Supports Progressive Disclosure Level 3+: converts relative file references\n to absolute paths so Agent can easily read nested resources.\n\n Args:\n content: Original skill content\n skill_dir: Skill directory path\n\n Returns:\n Processed content with absolute paths\n \"\"\"\n import re\n\n # Pattern 1: Directory-based paths (scripts/, references/, assets/)\n # See https://agentskills.io/specification#optional-directories\n def replace_dir_path(match):\n prefix = match.group(1) # e.g., \"python \" or \"`\"\n rel_path = match.group(2) # e.g., \"scripts/with_server.py\"\n\n abs_path = skill_dir / rel_path\n if abs_path.exists():\n return f\"{prefix}{abs_path}\"\n return match.group(0)\n\n pattern_dirs = r\"(python\\s+|`)((?:scripts|references|assets)/[^\\s`\\)]+)\"\n content = re.sub(pattern_dirs, replace_dir_path, content)\n\n # Pattern 2: Direct markdown/document references (forms.md, reference.md, etc.)\n # Matches phrases like \"see reference.md\" or \"read forms.md\"\n def replace_doc_path(match):\n prefix = match.group(1) # e.g., \"see \", \"read \"\n filename = match.group(2) # e.g., \"reference.md\"\n suffix = match.group(3) # e.g., punctuation\n\n abs_path = skill_dir / filename\n if abs_path.exists():\n # Add helpful instruction for Agent\n return f\"{prefix}`{abs_path}` (use read_file to access){suffix}\"\n return match.group(0)\n\n # Match patterns like: \"see reference.md\" or \"read forms.md\"\n pattern_docs = r\"(see|read|refer to|check)\\s+([a-zA-Z0-9_-]+\\.(?:md|txt|json|yaml))([.,;\\s])\"\n content = re.sub(pattern_docs, replace_doc_path, content, flags=re.IGNORECASE)\n\n # Pattern 3: Markdown links - supports multiple formats:\n # - [`filename.md`](filename.md) - simple filename\n # - [text](./reference/file.md) - relative path with ./\n # - [text](scripts/file.js) - directory-based path\n # Matches patterns like: \"Read [`docx-js.md`](docx-js.md)\" or \"Load [Guide](./reference/guide.md)\"\n def replace_markdown_link(match):\n prefix = match.group(1) if match.group(1) else \"\" # e.g., \"Read \", \"Load \", or empty\n link_text = match.group(2) # e.g., \"`docx-js.md`\" or \"Guide\"\n filepath = match.group(3) # e.g., \"docx-js.md\", \"./reference/file.md\", \"scripts/file.js\"\n\n # Remove leading ./ if present\n clean_path = filepath[2:] if filepath.startswith(\"./\") else filepath\n\n abs_path = skill_dir / clean_path\n if abs_path.exists():\n # Preserve the link text style (with or without backticks)\n return f\"{prefix}[{link_text}](`{abs_path}`) (use read_file to access)\"\n return match.group(0)\n\n # Match markdown link patterns with optional prefix words\n # Captures: (optional prefix word) [link text] (complete file path including ./)\n pattern_markdown = (\n r\"(?:(Read|See|Check|Refer to|Load|View)\\s+)?\\[(`?[^`\\]]+`?)\\]\\(((?:\\./)?[^)]+\\.(?:md|txt|json|yaml|js|py|html))\\)\"\n )\n content = re.sub(pattern_markdown, replace_markdown_link, content, flags=re.IGNORECASE)\n\n return content\n\n def discover_skills(self) -> List[Skill]:\n \"\"\"\n Discover and load all skills in the skills directory\n\n Returns:\n List of Skills\n \"\"\"\n skills = []\n\n if not self.skills_dir.exists():\n print(f\"⚠️ Skills directory does not exist: {self.skills_dir}\")\n return skills\n\n # Recursively find all SKILL.md files\n for skill_file in self.skills_dir.rglob(\"SKILL.md\"):\n skill = self.load_skill(skill_file)\n if skill:\n skills.append(skill)\n self.loaded_skills[skill.name] = skill\n\n return skills\n\n def get_skill(self, name: str) -> Optional[Skill]:\n \"\"\"\n Get loaded skill\n\n Args:\n name: Skill name\n\n Returns:\n Skill object, or None if not found\n \"\"\"\n return self.loaded_skills.get(name)\n\n def list_skills(self) -> List[str]:\n \"\"\"\n List all loaded skill names\n\n Returns:\n List of skill names\n \"\"\"\n return list(self.loaded_skills.keys())\n\n def get_skills_metadata_prompt(self) -> str:\n \"\"\"\n Generate prompt containing ONLY metadata (name + description) for all skills.\n This implements Progressive Disclosure - Level 1.\n\n Returns:\n Metadata-only prompt string\n \"\"\"\n if not self.loaded_skills:\n return \"\"\n\n prompt_parts = [\"## Available Skills\\n\"]\n prompt_parts.append(\"You have access to specialized skills. Each skill provides expert guidance for specific tasks.\\n\")\n prompt_parts.append(\"Load a skill's full content using the appropriate skill tool when needed.\\n\")\n\n # List all skills with their descriptions\n for skill in self.loaded_skills.values():\n prompt_parts.append(f\"- `{skill.name}`: {skill.description}\")\n\n return \"\\n\".join(prompt_parts)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 7912}, "tests/test_skill_tool.py::87": {"resolved_imports": ["mini_agent/tools/skill_loader.py", "mini_agent/tools/skill_tool.py"], "used_names": ["GetSkillTool", "Path", "create_skill_tools", "tempfile"], "enclosing_function": "test_create_skill_tools_returns_single_tool", "extracted_code": "# Source: mini_agent/tools/skill_tool.py\nclass GetSkillTool(Tool):\n \"\"\"Tool to get detailed information about a specific skill\"\"\"\n\n def __init__(self, skill_loader: SkillLoader):\n self.skill_loader = skill_loader\n\n @property\n def name(self) -> str:\n return \"get_skill\"\n\n @property\n def description(self) -> str:\n return \"Get complete content and guidance for a specified skill, used for executing specific types of tasks\"\n\n @property\n def parameters(self) -> Dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"skill_name\": {\n \"type\": \"string\",\n \"description\": \"Name of the skill to retrieve (use list_skills to view available skills)\",\n }\n },\n \"required\": [\"skill_name\"],\n }\n\n async def execute(self, skill_name: str) -> ToolResult:\n \"\"\"Get detailed information about specified skill\"\"\"\n skill = self.skill_loader.get_skill(skill_name)\n\n if not skill:\n available = \", \".join(self.skill_loader.list_skills())\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"Skill '{skill_name}' does not exist. Available skills: {available}\",\n )\n\n # Return complete skill content\n result = skill.to_prompt()\n return ToolResult(success=True, content=result)\n\ndef create_skill_tools(\n skills_dir: str = \"./skills\",\n) -> tuple[List[Tool], Optional[SkillLoader]]:\n \"\"\"\n Create skill tool for Progressive Disclosure\n\n Only provides get_skill tool - the agent uses metadata in system prompt\n to know what skills are available, then loads them on-demand.\n\n Args:\n skills_dir: Skills directory path\n\n Returns:\n Tuple of (list of tools, skill loader)\n \"\"\"\n # Create skill loader\n loader = SkillLoader(skills_dir)\n\n # Discover and load skills\n skills = loader.discover_skills()\n print(f\"✅ Discovered {len(skills)} Claude Skills\")\n\n # Create only the get_skill tool (Progressive Disclosure Level 2)\n tools = [\n GetSkillTool(loader),\n ]\n\n return tools, loader", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 2218}, "tests/test_skill_tool.py::89": {"resolved_imports": ["mini_agent/tools/skill_loader.py", "mini_agent/tools/skill_tool.py"], "used_names": ["GetSkillTool", "Path", "create_skill_tools", "tempfile"], "enclosing_function": "test_create_skill_tools_returns_single_tool", "extracted_code": "# Source: mini_agent/tools/skill_tool.py\nclass GetSkillTool(Tool):\n \"\"\"Tool to get detailed information about a specific skill\"\"\"\n\n def __init__(self, skill_loader: SkillLoader):\n self.skill_loader = skill_loader\n\n @property\n def name(self) -> str:\n return \"get_skill\"\n\n @property\n def description(self) -> str:\n return \"Get complete content and guidance for a specified skill, used for executing specific types of tasks\"\n\n @property\n def parameters(self) -> Dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"skill_name\": {\n \"type\": \"string\",\n \"description\": \"Name of the skill to retrieve (use list_skills to view available skills)\",\n }\n },\n \"required\": [\"skill_name\"],\n }\n\n async def execute(self, skill_name: str) -> ToolResult:\n \"\"\"Get detailed information about specified skill\"\"\"\n skill = self.skill_loader.get_skill(skill_name)\n\n if not skill:\n available = \", \".join(self.skill_loader.list_skills())\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"Skill '{skill_name}' does not exist. Available skills: {available}\",\n )\n\n # Return complete skill content\n result = skill.to_prompt()\n return ToolResult(success=True, content=result)\n\ndef create_skill_tools(\n skills_dir: str = \"./skills\",\n) -> tuple[List[Tool], Optional[SkillLoader]]:\n \"\"\"\n Create skill tool for Progressive Disclosure\n\n Only provides get_skill tool - the agent uses metadata in system prompt\n to know what skills are available, then loads them on-demand.\n\n Args:\n skills_dir: Skills directory path\n\n Returns:\n Tuple of (list of tools, skill loader)\n \"\"\"\n # Create skill loader\n loader = SkillLoader(skills_dir)\n\n # Discover and load skills\n skills = loader.discover_skills()\n print(f\"✅ Discovered {len(skills)} Claude Skills\")\n\n # Create only the get_skill tool (Progressive Disclosure Level 2)\n tools = [\n GetSkillTool(loader),\n ]\n\n return tools, loader", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 2218}, "tests/test_skill_tool.py::110": {"resolved_imports": ["mini_agent/tools/skill_loader.py", "mini_agent/tools/skill_tool.py"], "used_names": ["Path", "create_skill_tools", "tempfile"], "enclosing_function": "test_tool_count_optimization", "extracted_code": "# Source: mini_agent/tools/skill_tool.py\ndef create_skill_tools(\n skills_dir: str = \"./skills\",\n) -> tuple[List[Tool], Optional[SkillLoader]]:\n \"\"\"\n Create skill tool for Progressive Disclosure\n\n Only provides get_skill tool - the agent uses metadata in system prompt\n to know what skills are available, then loads them on-demand.\n\n Args:\n skills_dir: Skills directory path\n\n Returns:\n Tuple of (list of tools, skill loader)\n \"\"\"\n # Create skill loader\n loader = SkillLoader(skills_dir)\n\n # Discover and load skills\n skills = loader.discover_skills()\n print(f\"✅ Discovered {len(skills)} Claude Skills\")\n\n # Create only the get_skill tool (Progressive Disclosure Level 2)\n tools = [\n GetSkillTool(loader),\n ]\n\n return tools, loader", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 802}, "tests/test_skill_tool.py::59": {"resolved_imports": ["mini_agent/tools/skill_loader.py", "mini_agent/tools/skill_tool.py"], "used_names": ["GetSkillTool", "pytest"], "enclosing_function": "test_get_skill_tool", "extracted_code": "# Source: mini_agent/tools/skill_tool.py\nclass GetSkillTool(Tool):\n \"\"\"Tool to get detailed information about a specific skill\"\"\"\n\n def __init__(self, skill_loader: SkillLoader):\n self.skill_loader = skill_loader\n\n @property\n def name(self) -> str:\n return \"get_skill\"\n\n @property\n def description(self) -> str:\n return \"Get complete content and guidance for a specified skill, used for executing specific types of tasks\"\n\n @property\n def parameters(self) -> Dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"skill_name\": {\n \"type\": \"string\",\n \"description\": \"Name of the skill to retrieve (use list_skills to view available skills)\",\n }\n },\n \"required\": [\"skill_name\"],\n }\n\n async def execute(self, skill_name: str) -> ToolResult:\n \"\"\"Get detailed information about specified skill\"\"\"\n skill = self.skill_loader.get_skill(skill_name)\n\n if not skill:\n available = \", \".join(self.skill_loader.list_skills())\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"Skill '{skill_name}' does not exist. Available skills: {available}\",\n )\n\n # Return complete skill content\n result = skill.to_prompt()\n return ToolResult(success=True, content=result)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 1455}, "tests/test_terminal_utils.py::17": {"resolved_imports": ["mini_agent/utils/terminal_utils.py"], "used_names": ["calculate_display_width"], "enclosing_function": "test_ascii_text", "extracted_code": "# Source: mini_agent/utils/terminal_utils.py\ndef calculate_display_width(text: str) -> int:\n \"\"\"Calculate the visible width of text in terminal columns.\n\n This function correctly handles:\n - ANSI escape codes (removed from width calculation)\n - Emoji characters (counted as 2 columns)\n - East Asian Wide/Fullwidth characters (counted as 2 columns)\n - Combining characters (counted as 0 columns)\n - Regular ASCII characters (counted as 1 column)\n\n Args:\n text: Input text that may contain ANSI codes, emoji, or unicode characters\n\n Returns:\n Number of terminal columns the text will occupy when displayed\n\n Examples:\n >>> calculate_display_width(\"Hello\")\n 5\n >>> calculate_display_width(\"你好\")\n 4\n >>> calculate_display_width(\"🤖\")\n 2\n >>> calculate_display_width(\"\\033[31mRed\\033[0m\")\n 3\n \"\"\"\n # Remove ANSI escape codes (they don't occupy display space)\n clean_text = ANSI_ESCAPE_RE.sub(\"\", text)\n\n width = 0\n for char in clean_text:\n # Skip combining characters (zero width)\n if unicodedata.combining(char):\n continue\n\n code_point = ord(char)\n\n # Emoji range (most common emoji, counted as 2 columns)\n if EMOJI_START <= code_point <= EMOJI_END:\n width += 2\n continue\n\n # East Asian Width property\n # W = Wide, F = Fullwidth (both occupy 2 columns)\n eaw = unicodedata.east_asian_width(char)\n if eaw in (\"W\", \"F\"):\n width += 2\n else:\n width += 1\n\n return width", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1601}, "tests/test_terminal_utils.py::19": {"resolved_imports": ["mini_agent/utils/terminal_utils.py"], "used_names": ["calculate_display_width"], "enclosing_function": "test_ascii_text", "extracted_code": "# Source: mini_agent/utils/terminal_utils.py\ndef calculate_display_width(text: str) -> int:\n \"\"\"Calculate the visible width of text in terminal columns.\n\n This function correctly handles:\n - ANSI escape codes (removed from width calculation)\n - Emoji characters (counted as 2 columns)\n - East Asian Wide/Fullwidth characters (counted as 2 columns)\n - Combining characters (counted as 0 columns)\n - Regular ASCII characters (counted as 1 column)\n\n Args:\n text: Input text that may contain ANSI codes, emoji, or unicode characters\n\n Returns:\n Number of terminal columns the text will occupy when displayed\n\n Examples:\n >>> calculate_display_width(\"Hello\")\n 5\n >>> calculate_display_width(\"你好\")\n 4\n >>> calculate_display_width(\"🤖\")\n 2\n >>> calculate_display_width(\"\\033[31mRed\\033[0m\")\n 3\n \"\"\"\n # Remove ANSI escape codes (they don't occupy display space)\n clean_text = ANSI_ESCAPE_RE.sub(\"\", text)\n\n width = 0\n for char in clean_text:\n # Skip combining characters (zero width)\n if unicodedata.combining(char):\n continue\n\n code_point = ord(char)\n\n # Emoji range (most common emoji, counted as 2 columns)\n if EMOJI_START <= code_point <= EMOJI_END:\n width += 2\n continue\n\n # East Asian Width property\n # W = Wide, F = Fullwidth (both occupy 2 columns)\n eaw = unicodedata.east_asian_width(char)\n if eaw in (\"W\", \"F\"):\n width += 2\n else:\n width += 1\n\n return width", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1601}, "tests/test_terminal_utils.py::23": {"resolved_imports": ["mini_agent/utils/terminal_utils.py"], "used_names": ["calculate_display_width"], "enclosing_function": "test_empty_string", "extracted_code": "# Source: mini_agent/utils/terminal_utils.py\ndef calculate_display_width(text: str) -> int:\n \"\"\"Calculate the visible width of text in terminal columns.\n\n This function correctly handles:\n - ANSI escape codes (removed from width calculation)\n - Emoji characters (counted as 2 columns)\n - East Asian Wide/Fullwidth characters (counted as 2 columns)\n - Combining characters (counted as 0 columns)\n - Regular ASCII characters (counted as 1 column)\n\n Args:\n text: Input text that may contain ANSI codes, emoji, or unicode characters\n\n Returns:\n Number of terminal columns the text will occupy when displayed\n\n Examples:\n >>> calculate_display_width(\"Hello\")\n 5\n >>> calculate_display_width(\"你好\")\n 4\n >>> calculate_display_width(\"🤖\")\n 2\n >>> calculate_display_width(\"\\033[31mRed\\033[0m\")\n 3\n \"\"\"\n # Remove ANSI escape codes (they don't occupy display space)\n clean_text = ANSI_ESCAPE_RE.sub(\"\", text)\n\n width = 0\n for char in clean_text:\n # Skip combining characters (zero width)\n if unicodedata.combining(char):\n continue\n\n code_point = ord(char)\n\n # Emoji range (most common emoji, counted as 2 columns)\n if EMOJI_START <= code_point <= EMOJI_END:\n width += 2\n continue\n\n # East Asian Width property\n # W = Wide, F = Fullwidth (both occupy 2 columns)\n eaw = unicodedata.east_asian_width(char)\n if eaw in (\"W\", \"F\"):\n width += 2\n else:\n width += 1\n\n return width", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1601}, "tests/test_terminal_utils.py::27": {"resolved_imports": ["mini_agent/utils/terminal_utils.py"], "used_names": ["calculate_display_width"], "enclosing_function": "test_emoji", "extracted_code": "# Source: mini_agent/utils/terminal_utils.py\ndef calculate_display_width(text: str) -> int:\n \"\"\"Calculate the visible width of text in terminal columns.\n\n This function correctly handles:\n - ANSI escape codes (removed from width calculation)\n - Emoji characters (counted as 2 columns)\n - East Asian Wide/Fullwidth characters (counted as 2 columns)\n - Combining characters (counted as 0 columns)\n - Regular ASCII characters (counted as 1 column)\n\n Args:\n text: Input text that may contain ANSI codes, emoji, or unicode characters\n\n Returns:\n Number of terminal columns the text will occupy when displayed\n\n Examples:\n >>> calculate_display_width(\"Hello\")\n 5\n >>> calculate_display_width(\"你好\")\n 4\n >>> calculate_display_width(\"🤖\")\n 2\n >>> calculate_display_width(\"\\033[31mRed\\033[0m\")\n 3\n \"\"\"\n # Remove ANSI escape codes (they don't occupy display space)\n clean_text = ANSI_ESCAPE_RE.sub(\"\", text)\n\n width = 0\n for char in clean_text:\n # Skip combining characters (zero width)\n if unicodedata.combining(char):\n continue\n\n code_point = ord(char)\n\n # Emoji range (most common emoji, counted as 2 columns)\n if EMOJI_START <= code_point <= EMOJI_END:\n width += 2\n continue\n\n # East Asian Width property\n # W = Wide, F = Fullwidth (both occupy 2 columns)\n eaw = unicodedata.east_asian_width(char)\n if eaw in (\"W\", \"F\"):\n width += 2\n else:\n width += 1\n\n return width", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1601}, "tests/test_terminal_utils.py::33": {"resolved_imports": ["mini_agent/utils/terminal_utils.py"], "used_names": ["calculate_display_width"], "enclosing_function": "test_chinese_characters", "extracted_code": "# Source: mini_agent/utils/terminal_utils.py\ndef calculate_display_width(text: str) -> int:\n \"\"\"Calculate the visible width of text in terminal columns.\n\n This function correctly handles:\n - ANSI escape codes (removed from width calculation)\n - Emoji characters (counted as 2 columns)\n - East Asian Wide/Fullwidth characters (counted as 2 columns)\n - Combining characters (counted as 0 columns)\n - Regular ASCII characters (counted as 1 column)\n\n Args:\n text: Input text that may contain ANSI codes, emoji, or unicode characters\n\n Returns:\n Number of terminal columns the text will occupy when displayed\n\n Examples:\n >>> calculate_display_width(\"Hello\")\n 5\n >>> calculate_display_width(\"你好\")\n 4\n >>> calculate_display_width(\"🤖\")\n 2\n >>> calculate_display_width(\"\\033[31mRed\\033[0m\")\n 3\n \"\"\"\n # Remove ANSI escape codes (they don't occupy display space)\n clean_text = ANSI_ESCAPE_RE.sub(\"\", text)\n\n width = 0\n for char in clean_text:\n # Skip combining characters (zero width)\n if unicodedata.combining(char):\n continue\n\n code_point = ord(char)\n\n # Emoji range (most common emoji, counted as 2 columns)\n if EMOJI_START <= code_point <= EMOJI_END:\n width += 2\n continue\n\n # East Asian Width property\n # W = Wide, F = Fullwidth (both occupy 2 columns)\n eaw = unicodedata.east_asian_width(char)\n if eaw in (\"W\", \"F\"):\n width += 2\n else:\n width += 1\n\n return width", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1601}, "tests/test_terminal_utils.py::39": {"resolved_imports": ["mini_agent/utils/terminal_utils.py"], "used_names": ["calculate_display_width"], "enclosing_function": "test_japanese_characters", "extracted_code": "# Source: mini_agent/utils/terminal_utils.py\ndef calculate_display_width(text: str) -> int:\n \"\"\"Calculate the visible width of text in terminal columns.\n\n This function correctly handles:\n - ANSI escape codes (removed from width calculation)\n - Emoji characters (counted as 2 columns)\n - East Asian Wide/Fullwidth characters (counted as 2 columns)\n - Combining characters (counted as 0 columns)\n - Regular ASCII characters (counted as 1 column)\n\n Args:\n text: Input text that may contain ANSI codes, emoji, or unicode characters\n\n Returns:\n Number of terminal columns the text will occupy when displayed\n\n Examples:\n >>> calculate_display_width(\"Hello\")\n 5\n >>> calculate_display_width(\"你好\")\n 4\n >>> calculate_display_width(\"🤖\")\n 2\n >>> calculate_display_width(\"\\033[31mRed\\033[0m\")\n 3\n \"\"\"\n # Remove ANSI escape codes (they don't occupy display space)\n clean_text = ANSI_ESCAPE_RE.sub(\"\", text)\n\n width = 0\n for char in clean_text:\n # Skip combining characters (zero width)\n if unicodedata.combining(char):\n continue\n\n code_point = ord(char)\n\n # Emoji range (most common emoji, counted as 2 columns)\n if EMOJI_START <= code_point <= EMOJI_END:\n width += 2\n continue\n\n # East Asian Width property\n # W = Wide, F = Fullwidth (both occupy 2 columns)\n eaw = unicodedata.east_asian_width(char)\n if eaw in (\"W\", \"F\"):\n width += 2\n else:\n width += 1\n\n return width", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1601}, "tests/test_terminal_utils.py::44": {"resolved_imports": ["mini_agent/utils/terminal_utils.py"], "used_names": ["calculate_display_width"], "enclosing_function": "test_mixed_content", "extracted_code": "# Source: mini_agent/utils/terminal_utils.py\ndef calculate_display_width(text: str) -> int:\n \"\"\"Calculate the visible width of text in terminal columns.\n\n This function correctly handles:\n - ANSI escape codes (removed from width calculation)\n - Emoji characters (counted as 2 columns)\n - East Asian Wide/Fullwidth characters (counted as 2 columns)\n - Combining characters (counted as 0 columns)\n - Regular ASCII characters (counted as 1 column)\n\n Args:\n text: Input text that may contain ANSI codes, emoji, or unicode characters\n\n Returns:\n Number of terminal columns the text will occupy when displayed\n\n Examples:\n >>> calculate_display_width(\"Hello\")\n 5\n >>> calculate_display_width(\"你好\")\n 4\n >>> calculate_display_width(\"🤖\")\n 2\n >>> calculate_display_width(\"\\033[31mRed\\033[0m\")\n 3\n \"\"\"\n # Remove ANSI escape codes (they don't occupy display space)\n clean_text = ANSI_ESCAPE_RE.sub(\"\", text)\n\n width = 0\n for char in clean_text:\n # Skip combining characters (zero width)\n if unicodedata.combining(char):\n continue\n\n code_point = ord(char)\n\n # Emoji range (most common emoji, counted as 2 columns)\n if EMOJI_START <= code_point <= EMOJI_END:\n width += 2\n continue\n\n # East Asian Width property\n # W = Wide, F = Fullwidth (both occupy 2 columns)\n eaw = unicodedata.east_asian_width(char)\n if eaw in (\"W\", \"F\"):\n width += 2\n else:\n width += 1\n\n return width", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1601}, "tests/test_terminal_utils.py::49": {"resolved_imports": ["mini_agent/utils/terminal_utils.py"], "used_names": ["calculate_display_width"], "enclosing_function": "test_ansi_codes_ignored", "extracted_code": "# Source: mini_agent/utils/terminal_utils.py\ndef calculate_display_width(text: str) -> int:\n \"\"\"Calculate the visible width of text in terminal columns.\n\n This function correctly handles:\n - ANSI escape codes (removed from width calculation)\n - Emoji characters (counted as 2 columns)\n - East Asian Wide/Fullwidth characters (counted as 2 columns)\n - Combining characters (counted as 0 columns)\n - Regular ASCII characters (counted as 1 column)\n\n Args:\n text: Input text that may contain ANSI codes, emoji, or unicode characters\n\n Returns:\n Number of terminal columns the text will occupy when displayed\n\n Examples:\n >>> calculate_display_width(\"Hello\")\n 5\n >>> calculate_display_width(\"你好\")\n 4\n >>> calculate_display_width(\"🤖\")\n 2\n >>> calculate_display_width(\"\\033[31mRed\\033[0m\")\n 3\n \"\"\"\n # Remove ANSI escape codes (they don't occupy display space)\n clean_text = ANSI_ESCAPE_RE.sub(\"\", text)\n\n width = 0\n for char in clean_text:\n # Skip combining characters (zero width)\n if unicodedata.combining(char):\n continue\n\n code_point = ord(char)\n\n # Emoji range (most common emoji, counted as 2 columns)\n if EMOJI_START <= code_point <= EMOJI_END:\n width += 2\n continue\n\n # East Asian Width property\n # W = Wide, F = Fullwidth (both occupy 2 columns)\n eaw = unicodedata.east_asian_width(char)\n if eaw in (\"W\", \"F\"):\n width += 2\n else:\n width += 1\n\n return width", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1601}, "tests/test_terminal_utils.py::58": {"resolved_imports": ["mini_agent/utils/terminal_utils.py"], "used_names": ["calculate_display_width"], "enclosing_function": "test_combining_characters", "extracted_code": "# Source: mini_agent/utils/terminal_utils.py\ndef calculate_display_width(text: str) -> int:\n \"\"\"Calculate the visible width of text in terminal columns.\n\n This function correctly handles:\n - ANSI escape codes (removed from width calculation)\n - Emoji characters (counted as 2 columns)\n - East Asian Wide/Fullwidth characters (counted as 2 columns)\n - Combining characters (counted as 0 columns)\n - Regular ASCII characters (counted as 1 column)\n\n Args:\n text: Input text that may contain ANSI codes, emoji, or unicode characters\n\n Returns:\n Number of terminal columns the text will occupy when displayed\n\n Examples:\n >>> calculate_display_width(\"Hello\")\n 5\n >>> calculate_display_width(\"你好\")\n 4\n >>> calculate_display_width(\"🤖\")\n 2\n >>> calculate_display_width(\"\\033[31mRed\\033[0m\")\n 3\n \"\"\"\n # Remove ANSI escape codes (they don't occupy display space)\n clean_text = ANSI_ESCAPE_RE.sub(\"\", text)\n\n width = 0\n for char in clean_text:\n # Skip combining characters (zero width)\n if unicodedata.combining(char):\n continue\n\n code_point = ord(char)\n\n # Emoji range (most common emoji, counted as 2 columns)\n if EMOJI_START <= code_point <= EMOJI_END:\n width += 2\n continue\n\n # East Asian Width property\n # W = Wide, F = Fullwidth (both occupy 2 columns)\n eaw = unicodedata.east_asian_width(char)\n if eaw in (\"W\", \"F\"):\n width += 2\n else:\n width += 1\n\n return width", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1601}, "tests/test_terminal_utils.py::63": {"resolved_imports": ["mini_agent/utils/terminal_utils.py"], "used_names": ["calculate_display_width"], "enclosing_function": "test_complex_ansi_sequences", "extracted_code": "# Source: mini_agent/utils/terminal_utils.py\ndef calculate_display_width(text: str) -> int:\n \"\"\"Calculate the visible width of text in terminal columns.\n\n This function correctly handles:\n - ANSI escape codes (removed from width calculation)\n - Emoji characters (counted as 2 columns)\n - East Asian Wide/Fullwidth characters (counted as 2 columns)\n - Combining characters (counted as 0 columns)\n - Regular ASCII characters (counted as 1 column)\n\n Args:\n text: Input text that may contain ANSI codes, emoji, or unicode characters\n\n Returns:\n Number of terminal columns the text will occupy when displayed\n\n Examples:\n >>> calculate_display_width(\"Hello\")\n 5\n >>> calculate_display_width(\"你好\")\n 4\n >>> calculate_display_width(\"🤖\")\n 2\n >>> calculate_display_width(\"\\033[31mRed\\033[0m\")\n 3\n \"\"\"\n # Remove ANSI escape codes (they don't occupy display space)\n clean_text = ANSI_ESCAPE_RE.sub(\"\", text)\n\n width = 0\n for char in clean_text:\n # Skip combining characters (zero width)\n if unicodedata.combining(char):\n continue\n\n code_point = ord(char)\n\n # Emoji range (most common emoji, counted as 2 columns)\n if EMOJI_START <= code_point <= EMOJI_END:\n width += 2\n continue\n\n # East Asian Width property\n # W = Wide, F = Fullwidth (both occupy 2 columns)\n eaw = unicodedata.east_asian_width(char)\n if eaw in (\"W\", \"F\"):\n width += 2\n else:\n width += 1\n\n return width", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1601}, "tests/test_tool_schema.py::197": {"resolved_imports": ["mini_agent/tools/base.py"], "used_names": [], "enclosing_function": "test_multiple_tools", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_tool_schema.py::252": {"resolved_imports": ["mini_agent/tools/base.py"], "used_names": ["ToolResult", "pytest"], "enclosing_function": "test_tool_execute", "extracted_code": "# Source: mini_agent/tools/base.py\nclass ToolResult(BaseModel):\n \"\"\"Tool execution result.\"\"\"\n\n success: bool\n content: str = \"\"\n error: str | None = None", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 166}, "tests/test_tool_schema.py::145": {"resolved_imports": ["mini_agent/tools/base.py"], "used_names": [], "enclosing_function": "test_tool_to_schema", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_tool_schema.py::146": {"resolved_imports": ["mini_agent/tools/base.py"], "used_names": [], "enclosing_function": "test_tool_to_schema", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_tool_schema.py::175": {"resolved_imports": ["mini_agent/tools/base.py"], "used_names": [], "enclosing_function": "test_tool_schema_complex", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_tool_schema.py::157": {"resolved_imports": ["mini_agent/tools/base.py"], "used_names": [], "enclosing_function": "test_tool_to_openai_schema", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_tool_schema.py::220": {"resolved_imports": ["mini_agent/tools/base.py"], "used_names": [], "enclosing_function": "test_tool_with_enum", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_tool_schema.py::148": {"resolved_imports": ["mini_agent/tools/base.py"], "used_names": [], "enclosing_function": "test_tool_to_schema", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_tool_schema.py::199": {"resolved_imports": ["mini_agent/tools/base.py"], "used_names": [], "enclosing_function": "test_multiple_tools", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_tool_schema.py::143": {"resolved_imports": ["mini_agent/tools/base.py"], "used_names": [], "enclosing_function": "test_tool_to_schema", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_tool_schema.py::253": {"resolved_imports": ["mini_agent/tools/base.py"], "used_names": ["ToolResult", "pytest"], "enclosing_function": "test_tool_execute", "extracted_code": "# Source: mini_agent/tools/base.py\nclass ToolResult(BaseModel):\n \"\"\"Tool execution result.\"\"\"\n\n success: bool\n content: str = \"\"\n error: str | None = None", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 166}, "tests/test_tool_schema.py::171": {"resolved_imports": ["mini_agent/tools/base.py"], "used_names": [], "enclosing_function": "test_tool_schema_complex", "extracted_code": "", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_tools.py::85": {"resolved_imports": ["mini_agent/tools/bash_tool.py", "mini_agent/tools/file_tools.py"], "used_names": ["BashTool", "asyncio", "pytest"], "enclosing_function": "test_bash_tool", "extracted_code": "# Source: mini_agent/tools/bash_tool.py\nclass BashTool(Tool):\n \"\"\"Execute shell commands in foreground or background.\n\n Automatically detects OS and uses appropriate shell:\n - Windows: PowerShell\n - Unix/Linux/macOS: bash\n \"\"\"\n\n def __init__(self, workspace_dir: str | None = None):\n \"\"\"Initialize BashTool with OS-specific shell detection.\n\n Args:\n workspace_dir: Working directory for command execution.\n If provided, all commands run in this directory.\n If None, commands run in the process's cwd.\n \"\"\"\n self.is_windows = platform.system() == \"Windows\"\n self.shell_name = \"PowerShell\" if self.is_windows else \"bash\"\n self.workspace_dir = workspace_dir\n\n @property\n def name(self) -> str:\n return \"bash\"\n\n @property\n def description(self) -> str:\n shell_examples = {\n \"Windows\": \"\"\"Execute PowerShell commands in foreground or background.\n\nFor terminal operations like git, npm, docker, etc. DO NOT use for file operations - use specialized tools.\n\nParameters:\n - command (required): PowerShell command to execute\n - timeout (optional): Timeout in seconds (default: 120, max: 600) for foreground commands\n - run_in_background (optional): Set true for long-running commands (servers, etc.)\n\nTips:\n - Quote file paths with spaces: cd \"My Documents\"\n - Chain dependent commands with semicolon: git add . ; git commit -m \"msg\"\n - Use absolute paths instead of cd when possible\n - For background commands, monitor with bash_output and terminate with bash_kill\n\nExamples:\n - git status\n - npm test\n - python -m http.server 8080 (with run_in_background=true)\"\"\",\n \"Unix\": \"\"\"Execute bash commands in foreground or background.\n\nFor terminal operations like git, npm, docker, etc. DO NOT use for file operations - use specialized tools.\n\nParameters:\n - command (required): Bash command to execute\n - timeout (optional): Timeout in seconds (default: 120, max: 600) for foreground commands\n - run_in_background (optional): Set true for long-running commands (servers, etc.)\n\nTips:\n - Quote file paths with spaces: cd \"My Documents\"\n - Chain dependent commands with &&: git add . && git commit -m \"msg\"\n - Use absolute paths instead of cd when possible\n - For background commands, monitor with bash_output and terminate with bash_kill\n\nExamples:\n - git status\n - npm test\n - python3 -m http.server 8080 (with run_in_background=true)\"\"\",\n }\n return shell_examples[\"Windows\"] if self.is_windows else shell_examples[\"Unix\"]\n\n @property\n def parameters(self) -> dict[str, Any]:\n cmd_desc = f\"The {self.shell_name} command to execute. Quote file paths with spaces using double quotes.\"\n return {\n \"type\": \"object\",\n \"properties\": {\n \"command\": {\n \"type\": \"string\",\n \"description\": cmd_desc,\n },\n \"timeout\": {\n \"type\": \"integer\",\n \"description\": \"Optional: Timeout in seconds (default: 120, max: 600). Only applies to foreground commands.\",\n \"default\": 120,\n },\n \"run_in_background\": {\n \"type\": \"boolean\",\n \"description\": \"Optional: Set to true to run the command in the background. Use this for long-running commands like servers. You can monitor output using bash_output tool.\",\n \"default\": False,\n },\n },\n \"required\": [\"command\"],\n }\n\n async def execute(\n self,\n command: str,\n timeout: int = 120,\n run_in_background: bool = False,\n ) -> ToolResult:\n \"\"\"Execute shell command with optional background execution.\n\n Args:\n command: The shell command to execute\n timeout: Timeout in seconds (default: 120, max: 600)\n run_in_background: Set true to run command in background\n\n Returns:\n BashExecutionResult with command output and status\n \"\"\"\n\n try:\n # Validate timeout\n if timeout > 600:\n timeout = 600\n elif timeout < 1:\n timeout = 120\n\n # Prepare shell-specific command execution\n if self.is_windows:\n # Windows: Use PowerShell with appropriate encoding\n shell_cmd = [\"powershell.exe\", \"-NoProfile\", \"-Command\", command]\n else:\n # Unix/Linux/macOS: Use bash\n shell_cmd = command\n\n if run_in_background:\n # Background execution: Create isolated process\n bash_id = str(uuid.uuid4())[:8]\n\n # Start background process with combined stdout/stderr\n if self.is_windows:\n process = await asyncio.create_subprocess_exec(\n *shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.STDOUT,\n cwd=self.workspace_dir,\n )\n else:\n process = await asyncio.create_subprocess_shell(\n shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.STDOUT,\n cwd=self.workspace_dir,\n )\n\n # Create background shell and add to manager\n bg_shell = BackgroundShell(bash_id=bash_id, command=command, process=process, start_time=time.time())\n BackgroundShellManager.add(bg_shell)\n\n # Start monitoring task\n await BackgroundShellManager.start_monitor(bash_id)\n\n # Return immediately with bash_id\n message = f\"Command started in background. Use bash_output to monitor (bash_id='{bash_id}').\"\n formatted_content = f\"{message}\\n\\nCommand: {command}\\nBash ID: {bash_id}\"\n\n return BashOutputResult(\n success=True,\n content=formatted_content,\n stdout=f\"Background command started with ID: {bash_id}\",\n stderr=\"\",\n exit_code=0,\n bash_id=bash_id,\n )\n\n else:\n # Foreground execution: Create isolated process\n if self.is_windows:\n process = await asyncio.create_subprocess_exec(\n *shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n cwd=self.workspace_dir,\n )\n else:\n process = await asyncio.create_subprocess_shell(\n shell_cmd,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n cwd=self.workspace_dir,\n )\n\n try:\n stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)\n except asyncio.TimeoutError:\n process.kill()\n error_msg = f\"Command timed out after {timeout} seconds\"\n return BashOutputResult(\n success=False,\n error=error_msg,\n stdout=\"\",\n stderr=error_msg,\n exit_code=-1,\n )\n\n # Decode output\n stdout_text = stdout.decode(\"utf-8\", errors=\"replace\")\n stderr_text = stderr.decode(\"utf-8\", errors=\"replace\")\n\n # Create result (content auto-formatted by model_validator)\n is_success = process.returncode == 0\n error_msg = None\n if not is_success:\n error_msg = f\"Command failed with exit code {process.returncode}\"\n if stderr_text:\n error_msg += f\"\\n{stderr_text.strip()}\"\n\n return BashOutputResult(\n success=is_success,\n error=error_msg,\n stdout=stdout_text,\n stderr=stderr_text,\n exit_code=process.returncode or 0,\n )\n\n except Exception as e:\n return BashOutputResult(\n success=False,\n error=str(e),\n stdout=\"\",\n stderr=str(e),\n exit_code=-1,\n )", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 8734}, "tests/test_tools.py::48": {"resolved_imports": ["mini_agent/tools/bash_tool.py", "mini_agent/tools/file_tools.py"], "used_names": ["Path", "WriteTool", "asyncio", "pytest", "tempfile"], "enclosing_function": "test_write_tool", "extracted_code": "# Source: mini_agent/tools/file_tools.py\nclass WriteTool(Tool):\n \"\"\"Write content to a file.\"\"\"\n\n def __init__(self, workspace_dir: str = \".\"):\n \"\"\"Initialize WriteTool with workspace directory.\n\n Args:\n workspace_dir: Base directory for resolving relative paths\n \"\"\"\n self.workspace_dir = Path(workspace_dir).absolute()\n\n @property\n def name(self) -> str:\n return \"write_file\"\n\n @property\n def description(self) -> str:\n return (\n \"Write content to a file. Will overwrite existing files completely. \"\n \"For existing files, you should read the file first using read_file. \"\n \"Prefer editing existing files over creating new ones unless explicitly needed.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"type\": \"string\",\n \"description\": \"Absolute or relative path to the file\",\n },\n \"content\": {\n \"type\": \"string\",\n \"description\": \"Complete content to write (will replace existing content)\",\n },\n },\n \"required\": [\"path\", \"content\"],\n }\n\n async def execute(self, path: str, content: str) -> ToolResult:\n \"\"\"Execute write file.\"\"\"\n try:\n file_path = Path(path)\n # Resolve relative paths relative to workspace_dir\n if not file_path.is_absolute():\n file_path = self.workspace_dir / file_path\n\n # Create parent directories if they don't exist\n file_path.parent.mkdir(parents=True, exist_ok=True)\n\n file_path.write_text(content, encoding=\"utf-8\")\n return ToolResult(success=True, content=f\"Successfully wrote to {file_path}\")\n except Exception as e:\n return ToolResult(success=False, content=\"\", error=str(e))", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 2009}, "tests/test_tools.py::69": {"resolved_imports": ["mini_agent/tools/bash_tool.py", "mini_agent/tools/file_tools.py"], "used_names": ["EditTool", "Path", "asyncio", "pytest", "tempfile"], "enclosing_function": "test_edit_tool", "extracted_code": "# Source: mini_agent/tools/file_tools.py\nclass EditTool(Tool):\n \"\"\"Edit file by replacing text.\"\"\"\n\n def __init__(self, workspace_dir: str = \".\"):\n \"\"\"Initialize EditTool with workspace directory.\n\n Args:\n workspace_dir: Base directory for resolving relative paths\n \"\"\"\n self.workspace_dir = Path(workspace_dir).absolute()\n\n @property\n def name(self) -> str:\n return \"edit_file\"\n\n @property\n def description(self) -> str:\n return (\n \"Perform exact string replacement in a file. The old_str must match exactly \"\n \"and appear uniquely in the file, otherwise the operation will fail. \"\n \"You must read the file first before editing. Preserve exact indentation from the source.\"\n )\n\n @property\n def parameters(self) -> dict[str, Any]:\n return {\n \"type\": \"object\",\n \"properties\": {\n \"path\": {\n \"type\": \"string\",\n \"description\": \"Absolute or relative path to the file\",\n },\n \"old_str\": {\n \"type\": \"string\",\n \"description\": \"Exact string to find and replace (must be unique in file)\",\n },\n \"new_str\": {\n \"type\": \"string\",\n \"description\": \"Replacement string (use for refactoring, renaming, etc.)\",\n },\n },\n \"required\": [\"path\", \"old_str\", \"new_str\"],\n }\n\n async def execute(self, path: str, old_str: str, new_str: str) -> ToolResult:\n \"\"\"Execute edit file.\"\"\"\n try:\n file_path = Path(path)\n # Resolve relative paths relative to workspace_dir\n if not file_path.is_absolute():\n file_path = self.workspace_dir / file_path\n\n if not file_path.exists():\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"File not found: {path}\",\n )\n\n content = file_path.read_text(encoding=\"utf-8\")\n\n if old_str not in content:\n return ToolResult(\n success=False,\n content=\"\",\n error=f\"Text not found in file: {old_str}\",\n )\n\n new_content = content.replace(old_str, new_str)\n file_path.write_text(new_content, encoding=\"utf-8\")\n\n return ToolResult(success=True, content=f\"Successfully edited {file_path}\")\n except Exception as e:\n return ToolResult(success=False, content=\"\", error=str(e))", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 2669}}}