Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions agent_core/core/action_framework/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
from agent_core.core.action_framework.formatting import (
candidate_dict_from_action,
format_action_candidates,
format_actions_by_name,
)

__all__ = [
Expand All @@ -44,5 +43,4 @@
# Formatting
"candidate_dict_from_action",
"format_action_candidates",
"format_actions_by_name",
]
38 changes: 3 additions & 35 deletions agent_core/core/action_framework/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@
``account``).
- No ``example`` fields, no nested type-definitions.

Both ``ActionRouter`` (main agent) and ``SubAgentContextEngine`` (sub-agents)
should call ``format_action_candidates`` so the format stays in sync.
Every <actions> list (ActionRouter, for the main agent and sub-agents alike)
and every action_schemas event renders through ``format_action_candidates``.
"""

from __future__ import annotations

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


def candidate_dict_from_action(action) -> Dict[str, Any]:
Expand Down Expand Up @@ -119,39 +119,7 @@ def _params_every_action_takes(compact: List[Dict[str, Any]]) -> Dict[str, str]:
}


def format_actions_by_name(
action_names: List[str],
action_library,
*,
on_missing: Optional[str] = None,
) -> str:
"""Convenience: look up actions by name and render them.

Args:
action_names: Ordered list of action names to include.
action_library: Anything with ``retrieve_action(name) -> Action | None``.
on_missing: Optional log-message prefix for actions that aren't found;
when None, missing actions are silently skipped.

Returns:
Compact JSON block (or ``"[]"`` if nothing resolved).
"""
candidates: List[Dict[str, Any]] = []
for name in action_names:
act = action_library.retrieve_action(name)
if act is None:
if on_missing is not None:
# Use late import to avoid pulling logging deps at module load.
from agent_core.utils.logger import logger

logger.warning(f"{on_missing}: action {name!r} not found in library")
continue
candidates.append(candidate_dict_from_action(act))
return format_action_candidates(candidates)


__all__ = [
"candidate_dict_from_action",
"format_action_candidates",
"format_actions_by_name",
]
4 changes: 4 additions & 0 deletions agent_core/core/impl/action/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
OnActionEndHook,
GetParentIdHook,
)
from agent_core.core.impl.action.step import ActionCheck, AgentStep

__all__ = [
# Executor
Expand All @@ -37,4 +38,7 @@
"OnActionStartHook",
"OnActionEndHook",
"GetParentIdHook",
# Step
"ActionCheck",
"AgentStep",
]
142 changes: 80 additions & 62 deletions agent_core/core/impl/action/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@
import subprocess
import sys
import tempfile
import threading
import uuid
import venv
from pathlib import Path
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from typing import Any, Dict, List, Optional
from typing import Any, Dict, List, Optional, Set, Tuple

from agent_core.utils.logger import logger
from agent_core.utils.windows_process import hidden_console_kwargs
Expand All @@ -47,6 +48,13 @@
# Base packages that must be installed in the sandbox venv (empty - venv isolation is the sandbox)
_SANDBOX_BASE_PACKAGES = []

# Requirements settled in this process, as (python_bin, entry): confirmed
# installed, or not a pip package at all. Installed packages stay installed,
# so each is checked once instead of on every call (a ``pip show`` costs
# ~1.5 s). The lock makes concurrent first calls wait for one check.
_SETTLED_REQUIREMENTS: Set[Tuple[Optional[str], str]] = set()
_REQUIREMENTS_LOCK = threading.Lock()


class _HiddenEnvBuilder(venv.EnvBuilder):
"""Keep ensurepip's interpreter and installer children hidden too."""
Expand Down Expand Up @@ -203,69 +211,78 @@ def _ensure_requirements(
if not requirements:
return

pip_python = python_bin or _find_system_python()
if not pip_python:
logger.warning(
"[REQUIREMENTS] No Python interpreter found on PATH; cannot install packages."
)
return

installed_any = False
for pkg in requirements:
pkg = pkg.strip()
if not pkg:
continue

# Heuristic: skip entries that look like class names
# (e.g. "DDGS", "ClientSession", "build") rather than pip
# packages. Pip packages are lowercase and may contain
# hyphens/underscores/dots.
if not pkg[0].islower() and "-" not in pkg:
continue

# Derive the importable module name for the quick check.
# Only useful when NOT frozen (in-process imports work).
import_name = pkg.replace("-", "_").split("[")[0]

# First try a fast import check (works for most packages)
if not getattr(sys, "frozen", False):
with _REQUIREMENTS_LOCK:
pending = [
pkg
for pkg in (entry.strip() for entry in requirements)
if pkg and (python_bin, pkg) not in _SETTLED_REQUIREMENTS
]
if not pending:
return

pip_python = python_bin or _find_system_python()
if not pip_python:
logger.warning(
"[REQUIREMENTS] No Python interpreter found on PATH; cannot install packages."
)
return

installed_any = False
for pkg in pending:
# Heuristic: skip entries that look like class names
# (e.g. "DDGS", "ClientSession", "build") rather than pip
# packages. Pip packages are lowercase and may contain
# hyphens/underscores/dots.
if not pkg[0].islower() and "-" not in pkg:
_SETTLED_REQUIREMENTS.add((python_bin, pkg))
continue

# Derive the importable module name for the quick check.
# Only useful when NOT frozen (in-process imports work).
import_name = pkg.replace("-", "_").split("[")[0]

# First try a fast import check (works for most packages)
if not getattr(sys, "frozen", False):
try:
importlib.import_module(import_name)
_SETTLED_REQUIREMENTS.add((python_bin, pkg))
continue # already installed
except ImportError:
pass

# If import failed (or frozen), use pip show to check.
# This handles packages where pip name != import name
# (e.g., beautifulsoup4 -> bs4, Pillow -> PIL)
try:
importlib.import_module(import_name)
subprocess.check_call(
[str(pip_python), "-m", "pip", "show", "--quiet", pkg],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=15,
**hidden_console_kwargs(),
)
_SETTLED_REQUIREMENTS.add((python_bin, pkg))
continue # already installed
except ImportError:
except Exception:
pass

# If import failed (or frozen), use pip show to check.
# This handles packages where pip name != import name
# (e.g., beautifulsoup4 -> bs4, Pillow -> PIL)
try:
subprocess.check_call(
[str(pip_python), "-m", "pip", "show", "--quiet", pkg],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=15,
**hidden_console_kwargs(),
)
continue # already installed
except Exception:
pass

try:
subprocess.check_call(
[str(pip_python), "-m", "pip", "install", "--quiet", pkg],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=120,
**hidden_console_kwargs(),
)
installed_any = True
logger.info(f"[REQUIREMENTS] Installed '{pkg}'")
except Exception as e:
logger.warning(f"[REQUIREMENTS] Failed to install '{pkg}': {e}")
try:
subprocess.check_call(
[str(pip_python), "-m", "pip", "install", "--quiet", pkg],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=120,
**hidden_console_kwargs(),
)
installed_any = True
_SETTLED_REQUIREMENTS.add((python_bin, pkg))
logger.info(f"[REQUIREMENTS] Installed '{pkg}'")
except Exception as e:
logger.warning(f"[REQUIREMENTS] Failed to install '{pkg}': {e}")

# Refresh import caches so in-process exec() can find new packages.
if installed_any:
importlib.invalidate_caches()
# Refresh import caches so in-process exec() can find new packages.
if installed_any:
importlib.invalidate_caches()


def _suppress_worker_stdio():
Expand Down Expand Up @@ -558,7 +575,7 @@ def _atomic_action_internal(
) -> dict:
"""
Executes an internal action in-process (sync version).
Requirements are pre-installed at startup via install_all_action_requirements().
Requirements are ensured before the call (ActionExecutor.execute_atomic_action).
"""
try:
import inspect
Expand Down Expand Up @@ -730,10 +747,11 @@ async def execute_atomic_action(
)
logger.debug(f"[EXECUTION CODE] {action.code}")

# Pre-install declared pip requirements
# Pre-install declared pip requirements, off the event loop: a first
# check runs pip (seconds; an install, up to minutes).
requirements = getattr(action, "requirements", [])
if requirements and execution_mode == "internal":
_ensure_requirements(requirements)
await asyncio.to_thread(_ensure_requirements, requirements)

if execution_mode == "internal":
# Use async executor which handles both sync and async action functions
Expand Down
Loading